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

The following examples show how to use com.sun.net.httpserver.Headers#getFirst() . 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: HttpServer.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 votes vote down vote up
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;
}
 
Example 2
Source File: FileUploadDownloadClientTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange)
    throws IOException {
  Headers requestHeaders = httpExchange.getRequestHeaders();
  String uploadTypeStr = requestHeaders.getFirst(FileUploadDownloadClient.CustomHeaders.UPLOAD_TYPE);
  FileUploadType uploadType = FileUploadType.valueOf(uploadTypeStr);

  String downloadUri = null;

  if (uploadType == FileUploadType.JSON) {
    InputStream bodyStream = httpExchange.getRequestBody();
    downloadUri = JsonUtils.stringToJsonNode(IOUtils.toString(bodyStream, "UTF-8"))
        .get(CommonConstants.Segment.Offline.DOWNLOAD_URL).asText();
  } else if (uploadType == FileUploadType.URI) {
    downloadUri = requestHeaders.getFirst(FileUploadDownloadClient.CustomHeaders.DOWNLOAD_URI);
    String crypter = requestHeaders.getFirst(FileUploadDownloadClient.CustomHeaders.CRYPTER);
    Assert.assertEquals(crypter, TEST_CRYPTER);
  } else {
    Assert.fail();
  }
  Assert.assertEquals(downloadUri, TEST_URI);
  sendResponse(httpExchange, HttpStatus.SC_OK, "OK");
}
 
Example 3
Source File: PicqHttpServer.java    From PicqBotX with MIT License 5 votes vote down vote up
/**
 * 验证一个请求
 *
 * @param exchange 请求
 * @return 是否为 CoolQ Http 请求
 */
private boolean validateHeader(HttpExchange exchange)
{
    // 必须是 POST
    if (!exchange.getRequestMethod().toLowerCase().equals("post"))
    {
        return failed(INCORRECT_REQUEST_METHOD, "Not POST");
    }

    // 获取头
    Headers headers = exchange.getRequestHeaders();
    String contentType = headers.getFirst("content-type");
    String userAgent = headers.getFirst("user-agent");

    // 必须是 UTF-8
    if (!contentType.toLowerCase().contains("charset=utf-8"))
    {
        return failed(INCORRECT_CHARSET, "Not UTF-8");
    }

    // 必须是 JSON
    if (!contentType.contains("application/json"))
    {
        return failed(INCORRECT_APPLICATION_TYPE, "Not JSON");
    }

    // 判断版本
    if (!bot.getConfig().isNoVerify() && !userAgent.matches(HTTP_API_VERSION_DETECTION))
    {
        reportIncorrectVersion(userAgent);
        return failed(INCORRECT_VERSION, "Supported Version: " + HTTP_API_VERSION_DETECTION);
    }

    return true;
}
 
Example 4
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 5
Source File: ElevantoLoginDialog.java    From Quelea with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    if (isLoggedIn) {
        return;
    }
   
    URI uri = t.getRequestURI();
    String path = uri.getPath();
    
    // this work around send a javascript which calls a POST with the URL arguments so we can obtain them as 
    // HttpServer isnt passing them too us!
    if (path.equals("/oauth")){
        String msg = LabelGrabber.INSTANCE.getLabel("elevanto.loginsuccess.message");
        String response = "<html>\n" +
            "<script>\n" +
            "\n" +
            "   function closeWindow() {\n" +
            "        window.open('','_parent','');\n" +
            "        window.close();\n" +
            "   }\n" + 
            "\n" +
            "    function script() {\n" +
            "        var str = window.location.href;\n" +
            "        \n" +
            "        var xhttp = new XMLHttpRequest();\n" +
            "        xhttp.open(\"POST\", \"oauth_post\", true);\n" +
            "        xhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n" +
            "        xhttp.send(str);\n" +
            "        console.log(str);\n" +
            "        closeWindow();\n" +
            "    }\n" +
            "</script>\n" +
            "\n" +
            "<body onload=\"script();\">\n" +
            msg + "\n" + 
            "</body>\n" +
            "</html>";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
        return;
    }
    
    // source: https://stackoverflow.com/questions/3409348/read-post-request-values-httphandler
    Headers reqHeaders = t.getRequestHeaders();
    String contentType = reqHeaders.getFirst("Content-Type");
    String encoding = "ISO-8859-1";
    
    // read the query string from the request body
    String qry;
    InputStream in = t.getRequestBody();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte buf[] = new byte[4096];
        for (int n = in.read(buf); n > 0; n = in.read(buf)) {
            out.write(buf, 0, n);
        }
        qry = new String(out.toByteArray(), encoding);
    } finally {
        in.close();
    }
    
    String urlSplit[] = qry.split("[#]");
    String paramSplit[] = urlSplit[1].split("[&]");
    
    Map <String,String> params = new HashMap<String, String>();
    for (int i = 0; i < paramSplit.length; ++i) {
        String pair[] = paramSplit[i].split("=");
        if (pair.length>1) {
            params.put(pair[0], pair[1]);
        }else{
            params.put(pair[0], "");
        }
    }
    
    if (params.containsKey("access_token")) {
        String accessToken = (String)params.get("access_token");
        String refreshToken = (String)params.get("refresh_token");
        int expiresIn = Integer.parseInt(params.get("expires_in"));
        
        importDialog.getParser().setAccessToken(accessToken);
        isLoggedIn = true;
        importDialog.onLogin();
        hide();
    }
    else if (params.containsKey("error")) {
        String error = (String)params.get("error");
        String errorDesc = (String)params.get("error_description");
        
        LOGGER.log(Level.WARNING, "Error logging into Elevanto", errorDesc);
        Dialog.showWarning(LabelGrabber.INSTANCE.getLabel("pco.loginerror.title"), LabelGrabber.INSTANCE.getLabel("elevanto.loginerror.warning") + ":" + errorDesc);
    }

    shutdownServer();            
}
 
Example 6
Source File: RpcHandler.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * Handle an HTTP request
 *
 * @param exchange
 *            HTTP exchange
 * @throws IOException
 *             Error detected while handling the request
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
	try {
		int responseCode;
		String responseBody;
		//
		// Get the HTTP request
		//
		InetSocketAddress requestAddress = exchange.getRemoteAddress();
		String requestMethod = exchange.getRequestMethod();
		Headers requestHeaders = exchange.getRequestHeaders();
		String contentType = requestHeaders.getFirst("Content-Type");
		Headers responseHeaders = exchange.getResponseHeaders();
		BTCLoader.debug(String.format("%s request received from %s", requestMethod, requestAddress.getAddress()));
		if (!rpcAllowIp.contains(requestAddress.getAddress())) {
			responseCode = HttpURLConnection.HTTP_UNAUTHORIZED;
			responseBody = "Your IP address is not authorized to access this server";
			responseHeaders.set("Content-Type", "text/plain");
		} else if (!exchange.getRequestMethod().equals("POST")) {
			responseCode = HttpURLConnection.HTTP_BAD_METHOD;
			responseBody = String.format("%s requests are not supported", exchange.getRequestMethod());
			responseHeaders.set("Content-Type", "text/plain");
		} else if (contentType == null || !contentType.equals("application/json-rpc")) {
			responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
			responseBody = "Content type must be application/json-rpc";
			responseHeaders.set("Content-Type", "text/plain");
		} else {
			responseBody = processRequest(exchange);
			responseCode = HttpURLConnection.HTTP_OK;
			responseHeaders.set("Content-Type", "application/json-rpc");
		}
		//
		// Return the HTTP response
		//
		responseHeaders.set("Cache-Control", "no-cache, no-store, must-revalidate, private");
		responseHeaders.set("Server", "JavaBitcoin");
		byte[] responseBytes = responseBody.getBytes("UTF-8");
		exchange.sendResponseHeaders(responseCode, responseBytes.length);
		try (OutputStream out = exchange.getResponseBody()) {
			out.write(responseBytes);
		}
		BTCLoader.debug(String.format("RPC request from %s completed", requestAddress.getAddress()));
	} catch (IOException exc) {
		BTCLoader.error("Unable to process RPC request", exc);
		throw exc;
	}
}
 
Example 7
Source File: DefaultHttpClientTest.java    From spectator with Apache License 2.0 4 votes vote down vote up
private static int getInt(Headers headers, String k, int dflt) {
  String v = headers.getFirst(k);
  return (v == null) ? dflt : Integer.parseInt(v);
}