Java Code Examples for com.sun.net.httpserver.HttpExchange#getRequestURI()

The following examples show how to use com.sun.net.httpserver.HttpExchange#getRequestURI() . 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: MockQueryHandler.java    From vespa with Apache License 2.0 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    URI uri = t.getRequestURI();
    String query = uri.getQuery();
    String response = null;

    // Parse query - extract "query" element
    if (query != null) {
        String params[] = query.split("[&]");
        for (String param : params) {
            int i = param.indexOf('=');
            String name = param.substring(0, i);
            String value = URLDecoder.decode(param.substring(i + 1), "UTF-8");

            if ("query".equalsIgnoreCase(name)) {
                response = getResponse(URLDecoder.decode(param.substring(i + 1), "UTF-8"));
            }
        }
    }

    t.sendResponseHeaders(200, response == null ? 0 : response.length());
    OutputStream os = t.getResponseBody();
    os.write(response == null ? "".getBytes() : response.getBytes());
    os.close();

}
 
Example 2
Source File: EHHttpHandler.java    From easy-httpserver with Apache License 2.0 6 votes vote down vote up
/**
 * 解析参数
 */
private Map<String, Object> analysisParms(HttpExchange httpExchange)
		throws UnsupportedEncodingException {
	Map<String, Object> map = new HashMap<String, Object>();

	URI requestedUri = httpExchange.getRequestURI();
	String queryGet = requestedUri.getRawQuery();
	String queryPost = IOUtil.getRequestContent(httpExchange.getRequestBody());
	String query = "";
	if (!StringUtil.isEmpty(queryGet)) {
		query = queryGet;
	}
	if (!StringUtil.isEmpty(queryPost)) {
		query = StringUtil.isEmpty(query) ? queryPost : (query + "&" + queryPost);
	}
	if (StringUtil.isEmpty(query)) {
		return map;
	}

	for (String kv : query.split("&")) {
		String[] temp = kv.split("=");
		map.put(temp[0], URLDecoder.decode(temp[1], "utf-8"));
	}
	return map;
}
 
Example 3
Source File: AbstractHandler.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
/**
 * 处理请求头。
 */
public void handleHeader(HttpExchange httpEx) {
    InetSocketAddress remoteAddress = httpEx.getRemoteAddress();
    _logger.info("收到来自"+remoteAddress.getAddress().getHostAddress()+":"+remoteAddress.getPort()+"的请求");
    
    URI rUri = httpEx.getRequestURI();
    _logger.info("请求地址:"+rUri.toString());
    
    String method = httpEx.getRequestMethod();
    _logger.info("请求方法:"+method);
    
    Headers headers = httpEx.getRequestHeaders();
    Set<Entry<String, List<String>>> headerSet = headers.entrySet();
    _logger.info("请求头:");
    for (Entry<String, List<String>> header : headerSet) {
        _logger.info(header.getKey()+":"+header.getValue());
    }
}
 
Example 4
Source File: DefaultMetricsEndpointHttpHandler.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
	URI requestedUri = he.getRequestURI();
	this.headers = he.getRequestHeaders();
	
	Assert.assertEquals("/metrics", requestedUri.getPath());
	
	if (this.delayInMillis > 0) {
		try {
			Thread.sleep(this.delayInMillis);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			Assert.fail("Unexpected interruption of mocking environment");
		}
	}
	
	// send response
	he.sendResponseHeaders(200, this.response.length());
	
	OutputStream os = he.getResponseBody();
	os.write(response.getBytes());
	os.flush();
}
 
Example 5
Source File: Basic.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

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

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 6
Source File: Basic.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

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

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 7
Source File: MiniFDSRestserver.java    From galaxy-fds-sdk-java with Apache License 2.0 5 votes vote down vote up
private void handleInstruction(HttpExchange httpExchange) throws FDSException {
  URI uri = httpExchange.getRequestURI();
  String uriStr = uri.getPath();
  int random5xx = 500 + (new Random().nextInt(100));
  if (uriStr.substring(1).startsWith(CAUSE_5XX_INSTRUCTION)) {
    throw new FDSException(random5xx, CAUSE_5XX_INSTRUCTION);
  } else if (uriStr.substring(1).startsWith(CAUSE_5XX_ON_IP_INSTRUCTION)) {
    String remoteIp = httpExchange.getRemoteAddress().getAddress().getHostAddress();
    if (uriStr.contains(remoteIp)) {
      throw new FDSException(random5xx, CAUSE_5XX_ON_IP_INSTRUCTION);
    }
  }
}
 
Example 8
Source File: MultiPointServer.java    From mil-sym-java with Apache License 2.0 5 votes vote down vote up
private void parseGetParameters(HttpExchange exchange)
    throws UnsupportedEncodingException {

    Map<String,String> parameters = new HashMap<String, String>();
    URI requestedUri = exchange.getRequestURI();
    String query = requestedUri.getRawQuery();
    parseQuery(query, parameters);
    exchange.setAttribute("parameters", parameters);
}
 
Example 9
Source File: DefaultOAuthHttpHandler.java    From promregator with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
	log.debug("Request was received at handler");
	this.counterCalled++;

	URI requestedUri = he.getRequestURI();

	Assert.assertEquals("/oauth/token", requestedUri.getPath());
	Assert.assertEquals("grant_type=client_credentials", requestedUri.getRawQuery());
	Assert.assertEquals("POST", he.getRequestMethod());

	// check the body
	InputStreamReader isr = new InputStreamReader(he.getRequestBody(), StandardCharsets.UTF_8);
	BufferedReader br = new BufferedReader(isr);
	String query = br.readLine();

	Assert.assertEquals("response_type=token", query);
	
	// check the credentials
	String authValue = he.getRequestHeaders().getFirst("Authorization");
	Assert.assertEquals("Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=", authValue);

	String contentTypeValue = he.getRequestHeaders().getFirst("Content-Type");
	Assert.assertEquals("application/json", contentTypeValue);
	
	// send response
	he.sendResponseHeaders(200, this.response.length());

	OutputStream os = he.getResponseBody();
	os.write(response.getBytes());
	os.flush();
}
 
Example 10
Source File: RefactoringMinerHttpServer.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private static void printRequestInfo(HttpExchange exchange) {
	System.out.println("-- headers --");
	Headers requestHeaders = exchange.getRequestHeaders();
	requestHeaders.entrySet().forEach(System.out::println);

	System.out.println("-- HTTP method --");
	String requestMethod = exchange.getRequestMethod();
	System.out.println(requestMethod);

	System.out.println("-- query --");
	URI requestURI = exchange.getRequestURI();
	String query = requestURI.getQuery();
	System.out.println(query);
}
 
Example 11
Source File: Basic.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

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

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 12
Source File: HttpRequestHandler.java    From deployment-examples with MIT License 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {

        //Create a response form the request query parameters
        URI uri = t.getRequestURI();
        String response = createResponseFromQueryParams(uri);
        System.out.println("Response: " + response);
        //Set the response header status and length
        t.sendResponseHeaders(HTTP_OK_STATUS, response.getBytes().length);
        //Write the response string
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
 
Example 13
Source File: RemoteControlServer.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
private void parseGetParameters(HttpExchange exchange)
        throws UnsupportedEncodingException {

    Map<String, Object> parameters = new HashMap<>();
    URI requestedUri = exchange.getRequestURI();
    String query = requestedUri.getRawQuery();
    parseQuery(query, parameters);
    exchange.setAttribute("parameters", parameters);
}
 
Example 14
Source File: LocalFileRepoOverHttp.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(final HttpExchange httpExchange) throws IOException {
    final URI requestURI = httpExchange.getRequestURI();
    Message.info("Handling " + httpExchange.getRequestMethod() + " request " + requestURI);
    final URI artifactURI;
    try {
        artifactURI = new URI(webContextRoot).relativize(requestURI);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    final Path localFilePath = localFileRepoRoot.resolve(artifactURI.toString());
    if (httpExchange.getRequestMethod().equals("HEAD")) {
        final boolean available = this.isPresent(localFilePath);
        if (!available) {
            httpExchange.sendResponseHeaders(404, -1);
        } else {
            httpExchange.sendResponseHeaders(200, -1);
        }
        return;
    }
    if (!httpExchange.getRequestMethod().equals("GET")) {
        throw new IOException("Cannot handle " + httpExchange.getRequestMethod() + " HTTP method");
    }
    final OutputStream responseStream = httpExchange.getResponseBody();
    @SuppressWarnings("unused")
    final int numBytes = this.serve(httpExchange, localFilePath, responseStream);
    responseStream.close();
}
 
Example 15
Source File: MiniFDSRestserver.java    From galaxy-fds-sdk-java with Apache License 2.0 5 votes vote down vote up
private void FDSBucketOperation(HttpExchange httpExchange) throws UnsupportedEncodingException, FDS400Exception {
  URI uri = httpExchange.getRequestURI();
  if (HttpMethod.PUT.name().equalsIgnoreCase(httpExchange.getRequestMethod())) {
    if (splitQuery(uri).isEmpty()) {
      createBucket(uri.getPath().substring(1).split("/")[0]);
    }
  }
}
 
Example 16
Source File: HttpHandlerContainer.java    From metrics with Apache License 2.0 5 votes vote down vote up
private URI getRequestUri(final HttpExchange exchange, final URI baseUri) {
    try {
        return new URI(getServerAddress(baseUri) + exchange.getRequestURI());
    } catch (URISyntaxException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example 17
Source File: Basic.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

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

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 18
Source File: HttpHandlerContainer.java    From metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(final HttpExchange exchange) throws IOException {
    /**
     * This is a URI that contains the path, query and fragment components.
     */
    URI exchangeUri = exchange.getRequestURI();

    /**
     * The base path specified by the HTTP context of the HTTP handler. It
     * is in decoded form.
     */
    String decodedBasePath = exchange.getHttpContext().getPath();

    // Ensure that the base path ends with a '/'
    if (!decodedBasePath.endsWith("/")) {
        if (decodedBasePath.equals(exchangeUri.getPath())) {
            /**
             * This is an edge case where the request path does not end in a
             * '/' and is equal to the context path of the HTTP handler.
             * Both the request path and base path need to end in a '/'
             * Currently the request path is modified.
             *
             * TODO support redirection in accordance with resource configuration feature.
             */
            exchangeUri = UriBuilder.fromUri(exchangeUri)
                    .path("/").build();
        }
        decodedBasePath += "/";
    }

    /*
     * The following is madness, there is no easy way to get the complete
     * URI of the HTTP request!!
     *
     * TODO this is missing the user information component, how can this be obtained?
     */
    final boolean isSecure = exchange instanceof HttpsExchange;
    final String scheme = isSecure ? "https" : "http";

    final URI baseUri = getBaseUri(exchange, decodedBasePath, scheme);
    final URI requestUri = getRequestUri(exchange, baseUri);

    final ResponseWriter responseWriter = new ResponseWriter(exchange);
    final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri,
            exchange.getRequestMethod(), getSecurityContext(exchange.getPrincipal(), isSecure),
            new MapPropertiesDelegate());
    requestContext.setEntityStream(exchange.getRequestBody());
    requestContext.getHeaders().putAll(exchange.getRequestHeaders());
    requestContext.setWriter(responseWriter);
    try {
        appHandler.handle(requestContext);
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error handling request: ", e);
    } finally {
        // if the response was not committed yet by the JerseyApplication
        // then commit it and log warning
        responseWriter.closeAndLogWarning();
    }
}
 
Example 19
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 20
Source File: NacosConfigHttpHandler.java    From nacos-spring-project with Apache License 2.0 3 votes vote down vote up
/**
 * Handle {@link ConfigService#removeConfig(String, String)}
 *
 * @param httpExchange {@link HttpExchange}
 * @throws IOException IO error
 */
private void handleRemoveConfig(HttpExchange httpExchange) throws IOException {

	URI requestURI = httpExchange.getRequestURI();

	String queryString = requestURI.getQuery();

	Map<String, String> params = parseParams(queryString);

	String key = createContentKey(params);

	contentCache.remove(key);

	write(httpExchange, "OK");
}