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

The following examples show how to use com.sun.net.httpserver.HttpExchange#getRequestBody() . 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: AbstractHandler.java    From mateplus with GNU General Public License v2.0 6 votes vote down vote up
protected String getContent(HttpExchange exchange) throws IOException {
	/*
	 * It would be nice to not assume UTF8 below, but I don't know how to do
	 * that. Maybe escaping is actually done with HTML escapes. I should
	 * read up on this. For now I leave it like this.
	 */

	BufferedReader httpInput = new BufferedReader(new InputStreamReader(
			exchange.getRequestBody(), "UTF-8"));
	StringBuilder in = new StringBuilder();
	String input;
	while ((input = httpInput.readLine()) != null) {
		in.append(input).append(" ");
	}
	httpInput.close();
	return in.toString().trim();
}
 
Example 2
Source File: B6401598.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void handle(HttpExchange arg0) throws IOException {
        try {
                InputStream is = arg0.getRequestBody();
                OutputStream os = arg0.getResponseBody();

                DataInputStream dis = new DataInputStream(is);

                short input = dis.readShort();
                while (dis.read() != -1) ;
                dis.close();

                DataOutputStream dos = new DataOutputStream(os);

                arg0.sendResponseHeaders(200, 0);

                dos.writeShort(input);

                dos.flush();
                dos.close();
        } catch (IOException e) {
                e.printStackTrace();
                error = true;
        }
}
 
Example 3
Source File: Deadlock.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 4
Source File: WebApp.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    InputStream inputStream = t.getRequestBody();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String keyInput = URLDecoder.decode(reader.readLine().replace("key=", ""), Constant.CHARSET.displayName());

    String result;
    if (keyInput.equals("q") || keyInput.equals("S") || keyInput.equals("L")) {
        result = "";
    } else {
        result = KeyInputListener.doAction(keyInput, tableStat);
        if (result == null) {
            result = "";
        }
    }
    t.sendResponseHeaders(200, result.getBytes(Constant.CHARSET).length);
    OutputStream os = t.getResponseBody();
    os.write(result.getBytes(Constant.CHARSET));
    os.close();
}
 
Example 5
Source File: Deadlock.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 6
Source File: BasicLongCredentials.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();
    while (is.read () != -1) ;
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals(USERNAME)) {
        error = true;
    }
    if (!p.getRealm().equals(REALM)) {
        error = true;
    }
    t.close();
}
 
Example 7
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 8
Source File: BasicLongCredentials.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();
    while (is.read () != -1) ;
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals(USERNAME)) {
        error = true;
    }
    if (!p.getRealm().equals(REALM)) {
        error = true;
    }
    t.close();
}
 
Example 9
Source File: B8185898.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();
    InetSocketAddress rem = t.getRemoteAddress();
    headers = t.getRequestHeaders();    // Get request headers on the server side
    while(is.read() != -1){}
    is.close();

    OutputStream os = t.getResponseBody();
    t.sendResponseHeaders(200, RESPONSE_BODY.length());
    os.write(RESPONSE_BODY.getBytes(UTF_8));
    t.close();
}
 
Example 10
Source File: BasicLongCredentials.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();
    while (is.read () != -1) ;
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals(USERNAME)) {
        error = true;
    }
    if (!p.getRealm().equals(REALM)) {
        error = true;
    }
    t.close();
}
 
Example 11
Source File: BasicLongCredentials.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();
    while (is.read () != -1) ;
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals(USERNAME)) {
        error = true;
    }
    if (!p.getRealm().equals(REALM)) {
        error = true;
    }
    t.close();
}
 
Example 12
Source File: AuthFilter.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void consumeInput(HttpExchange t) throws IOException {
   InputStream i = t.getRequestBody();
   byte[] b = new byte[4096];

   while(i.read(b) != -1) {
      ;
   }

   i.close();
}
 
Example 13
Source File: BasicLongCredentials.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void handle (HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    while (is.read () != -1) ;
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals(USERNAME)) {
        error = true;
    }
    if (!p.getRealm().equals(REALM)) {
        error = true;
    }
    t.close();
}
 
Example 14
Source File: BasicLongCredentials.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();
    while (is.read () != -1) ;
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals(USERNAME)) {
        error = true;
    }
    if (!p.getRealm().equals(REALM)) {
        error = true;
    }
    t.close();
}
 
Example 15
Source File: InfiniteLoop.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 {
    InputStream is  = t.getRequestBody();
    byte[] ba = new byte[8192];
    while(is.read(ba) != -1);

    t.sendResponseHeaders(200, RESP_LENGTH);
    try (OutputStream os = t.getResponseBody()) {
        os.write(new byte[RESP_LENGTH]);
    }
    t.close();
}
 
Example 16
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 17
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 18
Source File: ClassLoad.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
     boolean error = true;

     // Start a dummy server to return 404
     HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
     HttpHandler handler = new HttpHandler() {
         public void handle(HttpExchange t) throws IOException {
             InputStream is = t.getRequestBody();
             while (is.read() != -1);
             t.sendResponseHeaders (404, -1);
             t.close();
         }
     };
     server.createContext("/", handler);
     server.start();

     // Client request
     try {
         URL url = new URL("http://localhost:" + server.getAddress().getPort());
         String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
         ClassLoader loader = new URLClassLoader(new URL[] { url });
         System.out.println(url);
         Class c = loader.loadClass(name);
         System.out.println("Loaded class \"" + c.getName() + "\".");
     } catch (ClassNotFoundException ex) {
         System.out.println(ex);
         error = false;
     } finally {
         server.stop(0);
     }
     if (error)
         throw new RuntimeException("No ClassNotFoundException generated");
}
 
Example 19
Source File: AbstractHttpHandler.java    From james with Apache License 2.0 4 votes vote down vote up
protected static String readRequestBodyAsString(HttpExchange exchange) throws IOException {
    InputStreamReader reader = new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8);
    return new BufferedReader(reader).lines().collect(Collectors.joining("\n"));
}
 
Example 20
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();            
}