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

The following examples show how to use com.sun.net.httpserver.Headers#set() . 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: ConsoleProxyAjaxHandler.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private void handleClientStart(HttpExchange t, ConsoleProxyClient viewer, String title, String guest) throws IOException {
    List<String> languages = t.getRequestHeaders().get("Accept-Language");
    String response = viewer.onAjaxClientStart(title, languages, guest);

    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());

    OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 2
Source File: ParkInetServer.java    From Fourinone with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: ParkInetServer.java    From Fourinone with Apache License 2.0 6 votes vote down vote up
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();
	}
}
 
Example 4
Source File: ConsoleProxyAjaxImageHandler.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(final HttpExchange t) throws IOException {
    try {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("AjaxImageHandler " + t.getRequestURI());
        }

        final long startTick = System.currentTimeMillis();

        doHandle(t);

        if (s_logger.isDebugEnabled()) {
            s_logger.debug(t.getRequestURI() + "Process time " + (System.currentTimeMillis() - startTick) + " ms");
        }
    } catch (final IllegalArgumentException e) {
        s_logger.warn("Exception, ", e);
        final Headers hds = t.getResponseHeaders();
        hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
        t.sendResponseHeaders(400, -1);     // bad request
    } finally {
        t.close();
    }
}
 
Example 5
Source File: ConsoleProxyCmdHandler.java    From cosmic with Apache License 2.0 6 votes vote down vote up
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");
        hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
        t.sendResponseHeaders(200, 0);
        final OutputStreamWriter os = new OutputStreamWriter(t.getResponseBody(), "UTF-8");
        statsCollector.getStatsReport(os);
        os.close();
    }
}
 
Example 6
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(final HttpExchange t) throws IOException {
    try {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("AjaxHandler " + t.getRequestURI());
        }

        final long startTick = System.currentTimeMillis();

        doHandle(t);

        if (s_logger.isTraceEnabled()) {
            s_logger.trace(t.getRequestURI() + " process time " + (System.currentTimeMillis() - startTick) + " ms");
        }
    } catch (final IllegalArgumentException e) {
        s_logger.warn("Exception, ", e);
        final Headers hds = t.getResponseHeaders();
        hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
        t.sendResponseHeaders(400, -1);     // bad request
    } finally {
        t.close();
    }
}
 
Example 7
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 6 votes vote down vote up
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");
    hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    t.sendResponseHeaders(200, response.length());

    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 8
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private void handleClientKickoff(final HttpExchange t, final ConsoleProxyClient viewer) throws IOException {
    final String response = viewer.onAjaxClientKickoff();
    final Headers hds = t.getResponseHeaders();
    hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    t.sendResponseHeaders(200, response.length());
    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 9
Source File: ConsoleProxyAjaxHandler.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void handleClientUpdate(HttpExchange t, ConsoleProxyClient viewer) throws IOException {
    String response = viewer.onAjaxClientUpdate();

    Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", "text/javascript");
    t.sendResponseHeaders(200, response.length());

    OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 10
Source File: ConsoleProxyAjaxHandler.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void sendResponse(HttpExchange t, String contentType, String response) throws IOException {
    Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", contentType);

    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 11
Source File: AbstractHandler.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 处理响应。
 */
public void handleResponse(HttpExchange httpEx, String content)
        throws UnsupportedEncodingException, IOException {
    String rc = "冒号后面是收到的请求,原样返回:"+content;
    byte[] temp = rc.getBytes(_charset);
    Headers outHeaders = httpEx.getResponseHeaders();
    outHeaders.set("ABC", "123");
    httpEx.sendResponseHeaders(200, temp.length);
    OutputStream outs = httpEx.getResponseBody();
    outs.write(temp);
    IOUtils.closeQuietly(outs);
}
 
Example 12
Source File: AuthHttpServer.java    From swift-explorer with Apache License 2.0 5 votes vote down vote up
@Override
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(200, 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<String> values = requestHeaders.get(key);
			String s = key + " = " + values.toString() + "\n";
			responseBody.write(s.getBytes());		
		}
		responseBody.close();
			
		if (sharedQueue != null)
		{
			String query = exchange.getRequestURI().getQuery() ;
			try 
			{
				sharedQueue.put(queryToParameterMap(query));
			} 
			catch (InterruptedException e) 
			{
				logger.error("Error occurred in the server handler", e);
			}
		}
	}
}
 
Example 13
Source File: ConsoleProxyThumbnailHandler.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(final HttpExchange t) throws IOException {
    try {
        Thread.currentThread().setName("JPG Thread " + Thread.currentThread().getId() + " " + t.getRemoteAddress());

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("ScreenHandler " + t.getRequestURI());
        }

        final long startTick = System.currentTimeMillis();
        doHandle(t);

        if (s_logger.isDebugEnabled()) {
            s_logger.debug(t.getRequestURI() + "Process time " + (System.currentTimeMillis() - startTick) + " ms");
        }
    } catch (final IllegalArgumentException e) {
        final String response = "Bad query string";
        s_logger.error(response + ", request URI : " + t.getRequestURI());
        final Headers hds = t.getResponseHeaders();
        hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
        t.sendResponseHeaders(200, response.length());
        final OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    } finally {
        t.close();
    }
}
 
Example 14
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private void handleClientUpdate(final HttpExchange t, final ConsoleProxyClient viewer) throws IOException {
    final String response = viewer.onAjaxClientUpdate();

    final Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", "text/javascript");
    hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    t.sendResponseHeaders(200, response.length());

    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 15
Source File: HTTPServer.java    From learnjavabug with MIT License 5 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
  String requestMethod = he.getRequestMethod();
  System.out.println(requestMethod + " " + he.getRequestURI().getPath() + (
      StringUtils.isEmpty(he.getRequestURI().getRawQuery()) ? ""
          : "?" + he.getRequestURI().getRawQuery()) + " " + he.getProtocol());
  if (requestMethod.equalsIgnoreCase("GET")) {
    Headers responseHeaders = he.getResponseHeaders();
    responseHeaders.set("Content-Type", contentType == null ? "application/json" : contentType);

    he.sendResponseHeaders(200, 0);
    // parse request
    OutputStream responseBody = he.getResponseBody();
    Headers requestHeaders = he.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();
      System.out.println(s);
    }
    System.out.println();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(he.getRequestBody()));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    for (;(line = bufferedReader.readLine()) != null;) {
      stringBuilder.append(line);
    }
    System.out.println(stringBuilder.toString());

    byte[] bytes = Files.toByteArray(new File(filePath == null ? HTTPServer.class.getClassLoader().getResource(clazz).getPath() : filePath));
    // send response
    responseBody.write(bytes);
    responseBody.close();
  }
}
 
Example 16
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private void sendResponse(final HttpExchange t, final String contentType, final String response) throws IOException {
    final Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", contentType);
    hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");

    t.sendResponseHeaders(200, response.length());
    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 17
Source File: SimpleHttpServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void moved(HttpExchange t) throws IOException {
    Headers req = t.getRequestHeaders();
    Headers map = t.getResponseHeaders();
    URI uri = t.getRequestURI();
    String host = req.getFirst("Host");
    String location = "http://" + host + uri.getPath() + "/";
    map.set("Content-Type", "text/html");
    map.set("Location", location);
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
Example 18
Source File: ParkInetServer.java    From Fourinone with Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException
{
	String uri = exchange.getRequestURI().getPath().substring(5);
	//System.out.println(exchange.getRemoteAddress()+" getPath:"+uri);
	File fl = new File(uri);
	//System.out.println(fl);
	//System.out.println(fl.exists());
	
	String requestMethod = exchange.getRequestMethod();
	if(requestMethod.equalsIgnoreCase("GET"))
	{	
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "application/x-download");
		//responseHeaders.set("Content-Disposition", "attachment; filename=abcd.bat");
		exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, fl.length());//HttpURLConnection.HTTP_OK,responseMsg.length();
		OutputStream responseBody = exchange.getResponseBody();
		FileAdapter fa = new FileAdapter(fl.getPath());
		byte[] bts = null;
		long begin=0,every=FileAdapter.k(512);
		while((bts=fa.getReader(begin, every).readAll())!=null){
			responseBody.write(bts);
			begin+=bts.length;
		}
		fa.close();
		responseBody.close();
	}
}
 
Example 19
Source File: SimpleHttpServer.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void handle(HttpExchange t)
        throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    OutputStream os = t.getResponseBody();
    URI uri = t.getRequestURI();
    String path = uri.getPath();


    while (is.read() != -1) ;
    is.close();

    File f = new File(_docroot, path);
    if (!f.exists()) {
        notfound(t, path);
        return;
    }

    String method = t.getRequestMethod();
    if (method.equals("HEAD")) {
        rmap.set("Content-Length", Long.toString(f.length()));
        t.sendResponseHeaders(200, -1);
        t.close();
    } else if (!method.equals("GET")) {
        t.sendResponseHeaders(405, -1);
        t.close();
        return;
    }

    if (path.endsWith(".html") || path.endsWith(".htm")) {
        rmap.set("Content-Type", "text/html");
    } else {
        rmap.set("Content-Type", "text/plain");
    }

    t.sendResponseHeaders (200, f.length());

    FileInputStream fis = new FileInputStream(f);
    int count = 0;
    try {
        byte[] buf = new byte[16 * 1024];
        int len;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
            count += len;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 20
Source File: App.java    From templates with MIT License 4 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    String requestBody = "";
    String method = t.getRequestMethod();

    if (method.equalsIgnoreCase("POST")) {
        InputStream inputStream = t.getRequestBody();
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        // StandardCharsets.UTF_8.name() > JDK 7
        requestBody = result.toString("UTF-8");
 }
    
    // System.out.println(requestBody);
    Headers reqHeaders = t.getRequestHeaders();
    Map<String, String> reqHeadersMap = new HashMap<String, String>();

    for (Map.Entry<String, java.util.List<String>> header : reqHeaders.entrySet()) {
        java.util.List<String> headerValues = header.getValue();
        if(headerValues.size() > 0) {
            reqHeadersMap.put(header.getKey(), headerValues.get(0));
        }
    }

    // for(Map.Entry<String, String> entry : reqHeadersMap.entrySet()) {
    //     System.out.println("Req header " + entry.getKey() + " " + entry.getValue());
    // }

    IRequest req = new Request(requestBody, reqHeadersMap,t.getRequestURI().getRawQuery(), t.getRequestURI().getPath());
    
    IResponse res = this.handler.Handle(req);

    String response = res.getBody();
    byte[] bytesOut = response.getBytes("UTF-8");

    Headers responseHeaders = t.getResponseHeaders();
    String contentType = res.getContentType();
    if(contentType.length() > 0) {
        responseHeaders.set("Content-Type", contentType);
    }

    for(Map.Entry<String, String> entry : res.getHeaders().entrySet()) {
        responseHeaders.set(entry.getKey(), entry.getValue());
    }

    t.sendResponseHeaders(res.getStatusCode(), bytesOut.length);

    OutputStream os = t.getResponseBody();
    os.write(bytesOut);
    os.close();

    System.out.println("Request / " + Integer.toString(bytesOut.length) +" bytes written.");
}