Java 类com.sun.net.httpserver.Headers 实例源码

项目:amr2Fred    文件:CompareHandler.java   
private void noTriple(HttpExchange he) {

        try {
            Headers responseHeaders = he.getResponseHeaders();
            FileHandler ext = new FileHandler();
            File tmp;
            responseHeaders.set(TYPE, PNG);
            ext.getFile(NOTRIPLE);
            tmp = new File(PAGESDIR + NOTRIPLE);
            he.sendResponseHeaders(200, tmp.length());
            try (OutputStream os = he.getResponseBody()) {
                Files.copy(tmp.toPath(), os);
                tmp.delete();
            }
        } catch (IOException ex) {
            Logger.getLogger(CompareHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
项目:elasticsearch_my    文件:RestClientSingleHostIntegTests.java   
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    StringBuilder body = new StringBuilder();
    try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) {
        char[] buffer = new char[256];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            body.append(buffer, 0, read);
        }
    }
    Headers requestHeaders = httpExchange.getRequestHeaders();
    Headers responseHeaders = httpExchange.getResponseHeaders();
    for (Map.Entry<String, List<String>> header : requestHeaders.entrySet()) {
        responseHeaders.put(header.getKey(), header.getValue());
    }
    httpExchange.getRequestBody().close();
    httpExchange.sendResponseHeaders(statusCode, body.length() == 0 ? -1 : body.length());
    if (body.length() > 0) {
        try (OutputStream out = httpExchange.getResponseBody()) {
            out.write(body.toString().getBytes(Consts.UTF_8));
        }
    }
    httpExchange.close();
}
项目:graphflow    文件:PlanViewerHttpServer.java   
@Override
public void handle(HttpExchange exchange) throws IOException {
    InputStream inputStream = exchange.getRequestBody();
    String query;
    String response;
    try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        query = scanner.useDelimiter("\\A").next();
        logger.info("Query: " + query);
        inputStream.close();
        response = queryServer(query, ReturnType.JSON);
    } catch (Exception e) {
        logger.info("ERROR", e);
        response = new Message("ERROR: " + e.getMessage(), true).toJson().toString();
    }

    // Add the header to avoid error:
    // “No 'Access-Control-Allow-Origin' header is present on the requested resource”
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.add("Access-Control-Allow-Origin", "*");
    exchange.sendResponseHeaders(200, response.length());

    OutputStream outputStream = exchange.getResponseBody();
    outputStream.write(response.getBytes());
    outputStream.close();
}
项目:secondbase    文件:PrometheusWebConsoleTest.java   
@Test
public void parseMetrics() throws IOException {
    final Counter counter = Counter
            .build("testcounter", "testdescription")
            .labelNames("one", "two")
            .register();
    counter.labels("1", "2").inc();
    final HttpExchange mockExchange = mock(HttpExchange.class);
    final OutputStream outputStream = new ByteArrayOutputStream();
    when(mockExchange.getResponseBody()).thenReturn(outputStream);
    final Headers headers = new Headers();
    when(mockExchange.getResponseHeaders()).thenReturn(headers);

    new PrometheusWebConsole().getServlet().handle(mockExchange);

    assertEquals(TextFormat.CONTENT_TYPE_004, headers.get("Content-Type").get(0));

    final String response = outputStream.toString();
    assertTrue(response.contains("# HELP testcounter testdescription"));
    assertTrue(response.contains("# TYPE testcounter counter"));
    assertTrue(response.contains("one=\"1\""));
    assertTrue(response.contains("two=\"2\""));
}
项目:WLT3Serial    文件:WebServerTestHelper.java   
public void handle(HttpExchange exchange) {
    try {
        exchange.getRequestMethod();
        exchange.getRequestBody().close();
        Headers respHeaders = null;
        if(!accessed && (source == null)) { //context hasn't been accessed before
            source = exchange.getRemoteAddress().getHostString();
            accessed = true;
            respHeaders = exchange.getResponseHeaders();
            respHeaders.add("Content-Type","text/plain");
            exchange.sendResponseHeaders(200,path.length());
            OutputStream os = exchange.getResponseBody();
            os.write(path.getBytes());
            os.flush();
            os.close();
            accessList.put(path,source);
        } else {
            respHeaders = exchange.getResponseHeaders();
            exchange.sendResponseHeaders(404,0);
            exchange.getResponseBody().close();
        }
    } catch(Exception e) {
        System.err.println("Unforeseen error occurred!");
        e.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:Security.java   
@Override
public synchronized void handle(HttpExchange t)
        throws IOException {
    byte[] buf = new byte[2048];
    System.out.println("Server: " + t.getRequestURI());
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }
    increment();
    if (count() == 1) {
        Headers map = t.getResponseHeaders();
        String redirect = "/redirect/bar.txt";
        map.add("Location", redirect);
        t.sendResponseHeaders(301, -1);
        t.close();
    } else {
        String response = "Hello world";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes(StandardCharsets.ISO_8859_1));
        t.close();
    }
}
项目:openjdk-jdk10    文件:SmokeTest.java   
@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 responseHeaders = t.getResponseHeaders();

    if (count++ < 1) {
        responseHeaders.add("Location", root + "/foo/" + count);
    } else {
        responseHeaders.add("Location", SmokeTest.midSizedFilename);
    }
    t.sendResponseHeaders(301, -1);
    t.close();
}
项目:openjdk-jdk10    文件:SmokeTest.java   
@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();
    String redirect = root + "/foo/" + Integer.toString(count);
    increment();
    map.add("Location", redirect);
    t.sendResponseHeaders(301, -1);
    t.close();
}
项目:openjdk-jdk10    文件:LightWeightHttpServer.java   
@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();
}
项目:openjdk-jdk10    文件:HeadersTest1.java   
@Override
public void handle(HttpExchange he) throws IOException {
    List<String> l = he.getRequestHeaders().get("X-Bar");
    if (!l.contains("foo1") || !l.contains("foo2")) {
        for (String s : l) {
            System.out.println("HH: " + s);
        }
        he.sendResponseHeaders(500, -1);
        he.close();
        return;
    }
    Headers h = he.getResponseHeaders();
    h.add("X-Foo-Response", "resp1");
    h.add("X-Foo-Response", "resp2");
    he.sendResponseHeaders(200, RESPONSE.length());
    OutputStream os = he.getResponseBody();
    os.write(RESPONSE.getBytes(US_ASCII));
    os.close();
}
项目:openjdk-jdk10    文件:HttpOnly.java   
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
项目:openjdk9    文件:LightWeightHttpServer.java   
@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();
}
项目:openjdk9    文件:HeadersTest1.java   
@Override
public void handle(HttpExchange he) throws IOException {
    String method = he.getRequestMethod();
    InputStream is = he.getRequestBody();
    List<String> l = he.getRequestHeaders().get("X-Bar");
    if (!l.contains("foo1") || !l.contains("foo2")) {
        for (String s : l)
            System.out.println("HH: " + s);
        he.sendResponseHeaders(500, -1);
        he.close();
        return;
    }
    Headers h = he.getResponseHeaders();
    h.add("X-Foo-Response", "resp1");
    h.add("X-Foo-Response", "resp2");
    he.sendResponseHeaders(200, RESPONSE.length());
    OutputStream os = he.getResponseBody();
    os.write(RESPONSE.getBytes(US_ASCII));
    os.close();
}
项目:DigitalMediaServer    文件:RemoteUtil.java   
/**
 * Write the given resource as an http response body.
 */
public boolean write(String filename, HttpExchange t) throws IOException {
    InputStream stream = getInputStream(filename);
    if (stream != null) {
        Headers headers = t.getResponseHeaders();
        if (!headers.containsKey("Content-Type")) {
            String mime = getContentType(filename);
            if (mime != null) {
                headers.add("Content-Type", mime);
            }
        }
        // Note: available() isn't officially guaranteed to return the full
        // stream length but effectively seems to do so in our context.
        t.sendResponseHeaders(200, stream.available());
        dump(stream, t.getResponseBody());
        return true;
    }
    return false;
}
项目:WatCA    文件:WebServer.java   
public void handle(HttpExchange t) throws IOException {
    URI requestedUri = t.getRequestURI();
    String query = requestedUri.getRawQuery();
    URL ycsb = new URL("http://" + hostYCSB + ":" + portYCSB + "?" + query);
    try {
        InputStream in = ycsb.openStream();
        Headers h = t.getResponseHeaders();
        h.add("Content-Type", "text/html");
        t.sendResponseHeaders(200, 0);
        OutputStream os = t.getResponseBody();
        int i;
        while ((i = in.read()) != -1) {
            os.write(i);
            os.flush();
        }
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:openbravo-pos    文件:JettyHttpExchange.java   
@Override
public Headers getRequestHeaders()
{
    Headers headers = new Headers();
    Enumeration en = _req.getHeaderNames();
    while (en.hasMoreElements())
    {
        String name = (String) en.nextElement();
        Enumeration en2 = _req.getHeaders(name);
        while (en2.hasMoreElements())
        {
            String value = (String) en2.nextElement();
            headers.add(name, value);
        }
    }
    return headers;
}
项目:cosmic    文件:ConsoleProxyCmdHandler.java   
public void doHandle(final HttpExchange t) throws IOException {
    final String path = t.getRequestURI().getPath();
    final int i = path.indexOf("/", 1);
    final String cmd = path.substring(i + 1);
    s_logger.info("Get CMD request for " + cmd);
    if (cmd.equals("getstatus")) {
        final ConsoleProxyClientStatsCollector statsCollector = ConsoleProxy.getStatsCollector();

        final Headers hds = t.getResponseHeaders();
        hds.set("Content-Type", "text/plain");
        t.sendResponseHeaders(200, 0);
        final OutputStreamWriter os = new OutputStreamWriter(t.getResponseBody(), "UTF-8");
        statsCollector.getStatsReport(os);
        os.close();
    }
}
项目:cosmic    文件:ConsoleProxyAjaxHandler.java   
private void handleClientStart(final HttpExchange t, final ConsoleProxyClient viewer, final String title, final String guest) throws IOException {
    final List<String> languages = t.getRequestHeaders().get("Accept-Language");
    final String response = viewer.onAjaxClientStart(title, languages, guest);

    final Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", "text/html");
    hds.set("Cache-Control", "no-cache");
    hds.set("Cache-Control", "no-store");
    t.sendResponseHeaders(200, response.length());

    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
项目:Disco    文件:TaxServer.java   
public void handle(HttpExchange t) throws IOException {

    {
        Headers h = t.getResponseHeaders();
        String type="text/plain";
        h.add("Content-Type", type);
    }

    String response=USAGE;
    if(verbose2){System.out.println("Sending: "+response);}

    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
}
项目:lab-materials    文件:ServerHandler.java   
private void sendResponse(HttpExchange httpExchange, Response response) {
    try (OutputStream os = httpExchange.getResponseBody()) {
        byte[] bytes = response.getBody().getBytes();

        Headers headers = httpExchange.getResponseHeaders();
        headers.add(Constants.REQUEST_HEADER_ACCESS_CONTROL,"*");
        httpExchange.sendResponseHeaders(response.getStatusCode(), bytes.length);

        os.write( bytes);
        // there is no need to close stream manually
        // as try-catch with auto-closable is used
        /**
         * {@see http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html}
         */
    } catch (IOException e) {
        logger.error("Could not send response", e);
    }
}
项目:lab-materials    文件:ServerHandler.java   
private void sendResponse(HttpExchange httpExchange, Response response) {
    try (OutputStream os = httpExchange.getResponseBody()) {
        byte[] bytes = response.getBody().getBytes();

        Headers headers = httpExchange.getResponseHeaders();
        headers.add(Constants.REQUEST_HEADER_ACCESS_CONTROL_ORIGIN,"*");
        httpExchange.sendResponseHeaders(response.getStatusCode(), bytes.length);

        os.write( bytes);
        // there is no need to close stream manually
        // as try-catch with auto-closable is used
        /**
         * {@see http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html}
         */
    } catch (IOException e) {
        logger.error("Could not send response", e);
    }
}
项目:heron    文件:NetworkUtilsTest.java   
@Test
public void testReadHttpRequestBody() throws Exception {
  byte[] expectedBytes = "TO READ".getBytes();
  InputStream is = Mockito.spy(new ByteArrayInputStream(expectedBytes));

  HttpExchange exchange = Mockito.mock(HttpExchange.class);
  Headers headers = Mockito.mock(Headers.class);
  Mockito.doReturn(Integer.toString(expectedBytes.length)).
      when(headers).getFirst(Matchers.anyString());

  Mockito.doReturn(headers).when(exchange).getRequestHeaders();
  Mockito.doReturn(is).when(exchange).getRequestBody();

  Assert.assertArrayEquals(expectedBytes, NetworkUtils.readHttpRequestBody(exchange));
  Mockito.verify(is, Mockito.atLeastOnce()).close();
}
项目:heron    文件:NetworkUtilsTest.java   
@Test
public void testReadHttpRequestBodyFail() throws Exception {
  HttpExchange exchange = Mockito.mock(HttpExchange.class);
  Headers headers = Mockito.mock(Headers.class);
  Mockito.doReturn(headers).when(exchange).getRequestHeaders();

  Mockito.doReturn("-1").
      when(headers).getFirst(Matchers.anyString());
  Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));

  Mockito.doReturn("10").
      when(headers).getFirst(Matchers.anyString());
  InputStream inputStream = Mockito.mock(InputStream.class);
  Mockito.doReturn(inputStream).when(exchange).getRequestBody();
  Mockito.doThrow(new IOException("Designed IO exception for testing"))
      .when(inputStream).read(Matchers.any(byte[].class), Matchers.anyInt(), Matchers.anyInt());
  Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));
  Mockito.verify(inputStream, Mockito.atLeastOnce()).close();
}
项目:JFaceUtils    文件:BaseHttpHandler.java   
protected Map<String, Object> buildSafeHeadersMap(final Headers headers) {
    final Map<String, Object> headersToLog = new TreeMap<String, Object>();
    for (final Entry<String, List<String>> entry : headers.entrySet()) {
        final String key = entry.getKey();
        if (key != null) {
            final String lowerCaseKey = key.toLowerCase();
            for (final String maskedHeaderKey : maskedHeaderKeys) {
                if (lowerCaseKey.contains(maskedHeaderKey)) {
                    headersToLog.put(key, "****");
                    break;
                }
            }
            if (!headersToLog.containsKey(key)) {
                headersToLog.put(key, entry.getValue());
            }
        }
    }
    return headersToLog;
}
项目:transfer-accelerator    文件:ServerStatus.java   
public void handle(HttpExchange exchange) throws IOException {
  String requestMethod = exchange.getRequestMethod();
  if (requestMethod.equalsIgnoreCase("GET")) {
    boolean isHealthy = serverWithStats.isHealthy();
    Headers responseHeaders = exchange.getResponseHeaders();
    String response = "{ \"version\" : \"" + serverWithStats.getVersion() + "\"}";
    if (isHealthy) {
      responseHeaders.set("Content-Type", "text/html");
      exchange.sendResponseHeaders(200, response.getBytes().length);
    } else {
      responseHeaders.set("Content-Type", "text/html");
      exchange.sendResponseHeaders(500, response.getBytes().length);
    }
    OutputStream responseBody = exchange.getResponseBody();
    Headers requestHeaders = exchange.getRequestHeaders();
    responseBody.write(response.getBytes());
    responseBody.close();
  }
}
项目:fourinone    文件:ParkInetServer.java   
public void handle(HttpExchange exchange) throws IOException
{
    /*InputStream is = t.getRequestBody();
    String response = "response ok";
    t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
    */
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "text/html");
    String response = ConfigContext.getRequest(ConfigContext.getProp("RSPE404"));
    exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, response.length());
    OutputStream os = exchange.getResponseBody();
    os.write(response.getBytes());
    os.close();
}
项目:fourinone    文件:ParkInetServer.java   
public void handle(HttpExchange exchange) throws IOException
{
    String requestMethod = exchange.getRequestMethod();
    if(requestMethod.equalsIgnoreCase("GET"))
    {
        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);

        OutputStream responseBody = exchange.getResponseBody();
        Headers requestHeaders = exchange.getRequestHeaders();
        Set<String> keySet = requestHeaders.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()){
            String key = iter.next();
            List values = requestHeaders.get(key);
            String s = key + " = " + values.toString() + "\n";
            responseBody.write(s.getBytes());
        }
        responseBody.close();
    }
}
项目:trap    文件:CORSUtil.java   
public static void setCors(Headers requestHeaders, Headers responseHeaders)
{

    String origin = requestHeaders.getFirst("Origin");

    if (origin == null)
        origin = "null";

    responseHeaders.set("Allow", "GET,PUT,POST,DELETE,OPTIONS");
    responseHeaders.set("Access-Control-Allow-Origin", origin);
    responseHeaders.set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
    responseHeaders.set("Access-Control-Allow-Headers", "Content-Type");
    responseHeaders.set("Access-Control-Request-Methods", "GET,PUT,POST,DELETE,OPTIONS");
    responseHeaders.set("Access-Control-Request-Headers", "Content-Type");
    responseHeaders.set("Access-Control-Max-Age", "3600");
}
项目:jflask    文件:App.java   
private String getCookie(HttpExchange r, String name) {
  Headers headers = r.getRequestHeaders();
  if (headers != null) {
    List<String> cookies = headers.get("Cookie");
    if (cookies != null) {
      for (String cookieString : cookies) {
        String[] tokens = cookieString.split("\\s*;\\s*");
        for (String token : tokens) {
          if (token.startsWith(name) && token.charAt(name.length()) == '=') {
            return token.substring(name.length() + 1);
          }
        }
      }
    }
  }
  return null;
}
项目:hsac-fitnesse-fixtures    文件:HttpServer.java   
protected Charset getCharSet(Headers heHeaders) {
    Charset charset = UTF8;
    String contentTypeHeader = heHeaders.getFirst(HTTP.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        try {
            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset contentTypeCharset = contentType.getCharset();
            if (contentTypeCharset != null) {
                charset = contentTypeCharset;
            }
        } catch (ParseException | UnsupportedCharsetException e) {
            // ignore, use default charset UTF8
        }
    }
    return charset;
}