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

The following examples show how to use com.sun.net.httpserver.HttpExchange#sendResponseHeaders() . 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: Response.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
public void send(@NotNull HttpExchange exchange) {
    String content = getContent();

    try {
        for (Map.Entry<String, String> entry : getHeaders().entrySet()) {
            exchange.getResponseHeaders().add(entry.getKey(), entry.getValue());
        }

        exchange.sendResponseHeaders(getStatus(), content.length());
        OutputStream os = exchange.getResponseBody();

        os.write(content.getBytes());
        os.close();
    } catch (IOException ignored) {
    }
}
 
Example 2
Source File: InternalHttpServer.java    From zxpoly with GNU General Public License v3.0 6 votes vote down vote up
private void handleMainPage(final HttpExchange exchange) throws IOException {
  final String linkToVideoStream = "http://" + this.getHttpAddress() + "/" + STREAM_RESOURCE;

  final String page = HTML_TEMPLATE.replace("${video.link}", linkToVideoStream)
      .replace("${video.mime}", this.mime);

  final Headers headers = exchange.getResponseHeaders();
  headers.add("Content-Type", "text/html");

  final byte[] content = page.getBytes(StandardCharsets.UTF_8);

  exchange.sendResponseHeaders(200, content.length);
  final OutputStream out = exchange.getResponseBody();
  out.write(content);
  out.flush();
  out.close();
}
 
Example 3
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 4
Source File: MultiAuthTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    String method = he.getRequestMethod();
    InputStream is = he.getRequestBody();
    if (method.equalsIgnoreCase("POST")) {
        String requestBody = new String(is.readAllBytes(), US_ASCII);
        if (!requestBody.equals(POST_BODY)) {
            he.sendResponseHeaders(500, -1);
            ok = false;
        } else {
            he.sendResponseHeaders(200, -1);
            ok = true;
        }
    } else { // GET
        he.sendResponseHeaders(200, RESPONSE.length());
        OutputStream os = he.getResponseBody();
        os.write(RESPONSE.getBytes(US_ASCII));
        os.close();
        ok = true;
    }
}
 
Example 5
Source File: B6401598.java    From dragonwell8_jdk 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 6
Source File: RemoteControlServer.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    if (RCHandler.isLoggedOn(he.getRemoteAddress().getAddress().toString())) {
        he.getResponseHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
        he.sendResponseHeaders(200, -1);
        RCHandler.setLyrics(he.getRequestURI().toString());
    } else {
        reload(he);
    }
}
 
Example 7
Source File: SpotifyHandler.java    From MediaMod with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Multithreading.runAsync(() -> handleRequest(t.getRequestURI().toString().replace("/callback/?code=", "").substring(0, t.getRequestURI().toString().replace("/callback/?code=", "").length() - 18)));

    String response = "<!DOCTYPE html>\n" +
            "<html>\n" +
            "  <head>\n" +
            "    <meta charset=\"utf-8\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
            "    <title>MediaMod</title>\n" +
            "    <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css\">\n" +
            "    <script defer src=\"https://use.fontawesome.com/releases/v5.3.1/js/all.js\"></script>\n" +
            "  </head>\n" +
            "  <body class=\"hero is-dark is-fullheight\">\n" +
            "  <section class=\"section has-text-centered\">\n" +
            "    <div class=\"container\">\n" +
            "      <img src=\"https://raw.githubusercontent.com/MediaModMC/MediaMod/master/src/main/resources/assets/mediamod/header.png\" width=\"400px\">" + "\n" +
            "      <h1 class=\"title\">\n" +
            "        Success!\n" +
            "      </h1>\n" +
            "      <p class=\"subtitle\">\n" +
            "        Please close this window and go back into Minecraft!\n" +
            "      </p>\n" +
            "    </div>\n" +
            "  </section>\n" +
            "  </body>\n" +
            "</html>";

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

    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
}
 
Example 8
Source File: MobileLyricsServer.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    String response;
    if (t.getRequestURI().toString().contains("all")) {
        response = allLyrics();
    } else {
        response = getLyrics(false);
    }
    byte[] bytes = response.getBytes("UTF-8");
    t.getResponseHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
    t.sendResponseHeaders(200, bytes.length);
    try (OutputStream os = t.getResponseBody()) {
        os.write(bytes);
    }
}
 
Example 9
Source File: JobEntryHTTP_PDI_18044_Test.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public void handle( HttpExchange httpExchange ) throws IOException {
  StringBuilder response = new StringBuilder();
  response.append( "<html><body>" );
  response.append( "hello " + httpExchange.getPrincipal().getUsername() );
  response.append( "</body></html>" );
  httpExchange.sendResponseHeaders( 200, response.length() );
  OutputStream out = httpExchange.getResponseBody();
  out.write( response.toString().getBytes() );
  out.close();
}
 
Example 10
Source File: ClassLoad.java    From jdk8u-dev-jdk 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 11
Source File: HttpsSocketFacTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, message.length());
    BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(t.getResponseBody(), "ISO8859-1"));
    writer.write(message, 0, message.length());
    writer.close();
    t.close();
}
 
Example 12
Source File: TestStackInstanceIdService.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
	httpExchange.sendResponseHeaders(200, this.instanceId.getBytes().length);

	OutputStream responseBody = httpExchange.getResponseBody();
	responseBody.write(this.instanceId.getBytes());
	responseBody.flush();
	responseBody.close();
}
 
Example 13
Source File: MonitorHandler.java    From binlake with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange exc) throws IOException {
    LogUtils.debug.debug("delay handle");

    // delay map
    Map<String, Object> d = new HashMap<>();

    String key; // ILeaderSelector key
    MetaInfo m;   // meta info
    Map<String, Object> mo; // monitor
    ILeaderSelector l; // leader selector
    IBinlogWorker w; // worker
    for (Map.Entry<String, ILeaderSelector> entry : lsm.entrySet()) {
        Map<String, Object> node = new HashMap<>();
        key = entry.getKey();
        l = entry.getValue();

        // initiate for each time
        if (l != null && (w = l.getWork()) != null) {
            if ((mo = w.monitor()) != null) {
                // take all monitor inside
                node.putAll(mo);
            }

            if ((m = l.getMetaInfo()) != null) {
                // leader version & meta version & candidates
                node.put("leaderVersion", m.getLeaderVersion());
                node.put("metaVersion", m.getDbInfo().getMetaVersion());
                node.put("candies", m.getCandidate());
            }
        }
        d.put(key, node);
    }

    exc.sendResponseHeaders(200, 0);
    OutputStream os = exc.getResponseBody();
    os.write(JsonUtils.ObjtoJson(d).getBytes());
    os.close();
}
 
Example 14
Source File: Basic.java    From openjdk-jdk9 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 15
Source File: L2ACPServer.java    From L2ACP-api with GNU General Public License v2.0 5 votes vote down vote up
@Override
     public void handle(HttpExchange t) {
     	try {
         String requestBody = read(t.getRequestBody());
         requestBody = AesCrypto.decryptRequest(requestBody);
         JsonElement jelement = new JsonParser().parse(requestBody);
         JsonObject  jobject = jelement.getAsJsonObject();
         	         
         String key = jobject.get("ApiKey").getAsString();
         if(key.equals(key))
         {
         	int requestId = Integer.parseInt(jobject.get("RequestId").getAsString());
         	L2ACPRequest request = L2ACPRequests.REQUESTS[requestId].newRequest(jobject);
         	
             Gson gson = new Gson();
             String jsonInString = gson.toJson(request.getResponse());
             String jsonResponse = jsonInString.toString();
             jsonResponse = AesCrypto.encryptRequest(jsonResponse);
             t.sendResponseHeaders(200, jsonResponse.length());
             OutputStream os = t.getResponseBody();
             os.write(jsonResponse.getBytes());
             os.close();
         }
         
     	} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
     }
 
Example 16
Source File: MetricsHttpServer.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    String responseString = "{}";
    httpExchange.sendResponseHeaders(200, responseString.length());
    OutputStream os = httpExchange.getResponseBody();
    os.write(responseString.getBytes());
    os.close();
}
 
Example 17
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendResponse(HttpExchange he) throws IOException {
    System.out.println(type + ": Got " + he.getRequestMethod()
            + ": " + he.getRequestURI()
            + "\n" + HTTPTestServer.toString(he.getRequestHeaders()));
    System.out.println(type + ": Redirecting to "
                       + (authType == HttpAuthType.PROXY305
                            ? "proxy" : "server"));
    he.getResponseHeaders().add(getLocation(),
        redirectTargetURL.toExternalForm().toString());
    he.sendResponseHeaders(get3XX(), 0);
    System.out.println(type + ": Sent back " + get3XX() + " "
         + getLocation() + ": " + redirectTargetURL.toExternalForm().toString());
}
 
Example 18
Source File: NoCache.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 19
Source File: MockHttpServer.java    From vespa with Apache License 2.0 4 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
}
 
Example 20
Source File: HttpNegotiateServer.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, 0);
    t.getResponseBody().write(CONTENT.getBytes());
    t.close();
}