Java Code Examples for com.sun.net.httpserver.Headers#add()

The following examples show how to use com.sun.net.httpserver.Headers#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InternalHttpServer.java    From zxpoly with GNU General Public License v3.0 7 votes vote down vote up
private void handleStreamData(final HttpExchange exchange) throws IOException {
  final Headers headers = exchange.getResponseHeaders();
  headers.add("Content-Type", this.mime);
  headers.add("Cache-Control", "no-cache, no-store");
  headers.add("Pragma", "no-cache");
  headers.add("Transfer-Encoding", "chunked");
  headers.add("Content-Transfer-Encoding", "binary");
  headers.add("Expires", "0");
  headers.add("Connection", "Keep-Alive");
  headers.add("Keep-Alive", "max");
  headers.add("Accept-Ranges", "none");

  exchange.sendResponseHeaders(200, 0);

  OutputStream os = exchange.getResponseBody();
  try {
    final TcpReader reader = this.tcpReaderRef.get();
    if (reader != null) {
      while (!stopped && !Thread.currentThread().isInterrupted()) {
        final byte[] data = reader.read();
        if (data != null) {
          os.write(data);
          os.flush();
        }
      }
    }
  } finally {
    os.close();
  }
}
 
Example 2
Source File: LightWeightHttpServer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public synchronized void handle(HttpExchange t)
        throws IOException {
    byte[] buf = new byte[2048];
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }

    Headers map = t.getResponseHeaders();

    if (count++ < 1) {
        map.add("Location", root + "/foo/" + count);
    } else {
        map.add("Location", SmokeTest.midSizedFilename);
    }
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
Example 3
Source File: DiagnosticsServer.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
	// Set required headers
	Headers headers = exchange.getResponseHeaders();
	headers.add("Content-type", "application/json");
	headers.add("Access-Control-Allow-Origin", "*");

	// Build the payload
	String response = registry.entrySet().stream()
		.map(DiagnosticsServer::registryEntryToJson)
		.collect(Collectors.joining(",", "[", "]"));

	// Write response
	exchange.sendResponseHeaders(200, response.length());
	OutputStream os = exchange.getResponseBody();
	os.write(response.getBytes());
	os.close();
}
 
Example 4
Source File: TestFaultSequenceExecutionForMalformedResponse.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    Headers headers = httpExchange.getResponseHeaders();
    headers.add("Content-Type", "text/xml");

    //response payload
    String response = "<a></b>";

    httpExchange.sendResponseHeaders(200, response.length());
    OutputStream responseStream = httpExchange.getResponseBody();
    try {
        responseStream.write(response.getBytes(Charset.defaultCharset()));
    } finally {
        responseStream.close();
    }
}
 
Example 5
Source File: SimpleHTTPServer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {

    //Add headers to response message
    if (responseHeaders != null) {
        Headers headers = httpExchange.getResponseHeaders();
        for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
            headers.add(entry.getKey(), entry.getValue());
        }
    }
    httpExchange.sendResponseHeaders(200, responsePayload.length());

    //Add response payload
    OutputStream responseStream = httpExchange.getResponseBody();
    try {
        responseStream.write(responsePayload.getBytes(Charset.defaultCharset()));
    } finally {
        responseStream.close();
    }
}
 
Example 6
Source File: UnmodifiableMaps.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 7
Source File: UnmodifiableMaps.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 8
Source File: UnmodifiableMaps.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 9
Source File: UnmodifiableMaps.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 10
Source File: ImmutableHeaders.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    String method = he.getRequestMethod();
    InputStream is = he.getRequestBody();
    Headers h = he.getResponseHeaders();
    h.add("X-Foo-Response", "resp");
    he.sendResponseHeaders(200, RESPONSE.length());
    OutputStream os = he.getResponseBody();
    os.write(RESPONSE.getBytes(US_ASCII));
    os.close();
}
 
Example 11
Source File: JobEntryHTTP_PDI_18044_Test.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override public void handle( HttpExchange httpExchange ) throws IOException {
  Headers h = httpExchange.getResponseHeaders();
  h.add( "Content-Type", "application/octet-stream" );
  httpExchange.sendResponseHeaders( 200, 0 );
  InputStream is = httpExchange.getRequestBody();
  OutputStream os = httpExchange.getResponseBody();
  int inputChar = -1;
  while ( ( inputChar = is.read() ) >= 0 ) {
    os.write( inputChar );
  }
  is.close();
  os.flush();
  os.close();
  httpExchange.close();
}
 
Example 12
Source File: UnmodifiableMaps.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 13
Source File: ResponseBuilder.java    From james with Apache License 2.0 5 votes vote down vote up
public void sendResponse(HTTPStatus responseStatus) throws IOException {
    Headers headers = exchange.getResponseHeaders();
    headers.add(HTTP_HEADER_SERVER, "James HTTP Server");
    if (contentType != null) {
        headers.add(HTTP_HEADER_CONTENT_TYPE, contentType.toString());
    }
    exchange.sendResponseHeaders(responseStatus.getCode(), responseBody != null ? responseBody.length : -1L);

    if (responseBody != null) {
        try (OutputStream outputStream = exchange.getResponseBody()) {
            outputStream.write(responseBody);
        }
    }
}
 
Example 14
Source File: UnmodifiableMaps.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 15
Source File: UnmodifiableMaps.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 16
Source File: ESBJAVA2283ReturnContentTypeTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {

            Headers h = t.getResponseHeaders();
            h.add("Content-Type", "text/xml");
            String response = "This is the test case for ESBJAVA-2283";
            t.sendResponseHeaders(HTTP_STATUS_OK, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
 
Example 17
Source File: LocalServerReceiver.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private void writeLandingHtml(HttpExchange exchange, Headers headers) throws IOException {
  OutputStream os = exchange.getResponseBody();
  exchange.sendResponseHeaders(HTTP_OK, 0);
  headers.add("ContentType", "text/html");

  PrintWriter doc = new PrintWriter(os);
  doc.println("<html>");
  doc.println("<head><title>OAuth 2.0 Authentication Token Received</title></head>");
  doc.println("<body>");
  doc.println("Received verification code. You may now close this window.");
  doc.println("</body>");
  doc.println("</html>");
  doc.flush();
  os.close();
}
 
Example 18
Source File: LocalServerReceiver.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {

  if (!callbackPath.equals(httpExchange.getRequestURI().getPath())) {
    return;
  }

  StringBuilder body = new StringBuilder();

  try {
    Map<String, String> parms =
        this.queryToMap(httpExchange.getRequestURI().getQuery());
    error = parms.get("error");
    code = parms.get("code");

    Headers respHeaders = httpExchange.getResponseHeaders();
    if (error == null && successLandingPageUrl != null) {
      respHeaders.add("Location", successLandingPageUrl);
      httpExchange.sendResponseHeaders(HTTP_MOVED_TEMP, -1);
    } else if (error != null && failureLandingPageUrl != null) {
      respHeaders.add("Location", failureLandingPageUrl);
      httpExchange.sendResponseHeaders(HTTP_MOVED_TEMP, -1);
    } else {
      writeLandingHtml(httpExchange, respHeaders);
    }
    httpExchange.close();
  } finally {
    waitUnlessSignaled.release();
  }
}
 
Example 19
Source File: ContentTypeTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {

            Headers h = t.getResponseHeaders();
            h.add("Content-Type", contentType);
            String response = "This Content type test case";
            t.sendResponseHeaders(HTTP_STATUS_OK, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
 
Example 20
Source File: HttpInteractor.java    From NCANode with MIT License 4 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    ApiServiceProvider api = HttpInteractor.this.provider.api;
    InfoServiceProvider info = HttpInteractor.this.provider.info;

    // headers
    Headers headers = exchange.getResponseHeaders();
    headers.add("X-Powered-By", info.getFullName());

    // streams
    OutputStream resp = exchange.getResponseBody();
    InputStream req  = exchange.getRequestBody();

    // Принимаем только POST запросы
    if (!exchange.getRequestMethod().equals("POST")) {
        headers.add("Content-Type", "text/plain; charset=UTF-8");
        String respString = info.getFullName() +" is started. Please use POST request method for work with API.";

        exchange.sendResponseHeaders(200, respString.length());
        resp.write(respString.getBytes());
        resp.close();
    } else {
        // handle request
        String response = "";
        headers.add("Content-Type", "application/json; charset=UTF-8");


        if (!exchange.getRequestHeaders().getFirst("Content-Type").equals("application/json")) {
            response = "Invalid header Content-Type. Please set Content-Type to application/json";
        } else {
            // read request body
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;

            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(req, "UTF-8"))) {
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }

            String requestBody = stringBuilder.toString();

            // Process request
            try {
                JSONObject requestJson = (JSONObject)(new JSONParser()).parse(requestBody);
                response = api.process(requestJson).toJSONString();
            } catch (ParseException e) {
                JSONObject re = new JSONObject();
                re.put("status", -1);
                re.put("message", "JSON parsing error");
                response = re.toJSONString();
            }
        }

        byte[] respBytes = response.getBytes(StandardCharsets.UTF_8);

        exchange.sendResponseHeaders(200, respBytes.length);
        resp.write(respBytes);
        resp.close();
        req.close();
        System.gc();
    }

}