当前位置: 首页>>代码示例>>Java>>正文


Java HttpExchange.getRequestBody方法代码示例

本文整理汇总了Java中com.sun.net.httpserver.HttpExchange.getRequestBody方法的典型用法代码示例。如果您正苦于以下问题:Java HttpExchange.getRequestBody方法的具体用法?Java HttpExchange.getRequestBody怎么用?Java HttpExchange.getRequestBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.sun.net.httpserver.HttpExchange的用法示例。


在下文中一共展示了HttpExchange.getRequestBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    StringBuilder body = new StringBuilder();
    try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) {
        char[] buffer = new char[256];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            body.append(buffer, 0, read);
        }
    }
    Headers requestHeaders = httpExchange.getRequestHeaders();
    Headers responseHeaders = httpExchange.getResponseHeaders();
    for (Map.Entry<String, List<String>> header : requestHeaders.entrySet()) {
        responseHeaders.put(header.getKey(), header.getValue());
    }
    httpExchange.getRequestBody().close();
    httpExchange.sendResponseHeaders(statusCode, body.length() == 0 ? -1 : body.length());
    if (body.length() > 0) {
        try (OutputStream out = httpExchange.getResponseBody()) {
            out.write(body.toString().getBytes(Consts.UTF_8));
        }
    }
    httpExchange.close();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:RestClientSingleHostIntegTests.java

示例2: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
public void handle(Pair<String, String> id, HttpExchange he, String[] path) throws Exception {
        Handler handler = handlers.get(id);
        if (handler == null) {
//            logger.log(Level.SEVERE, "Missing handler: {0}", id);
            handler = handlers.get(null);
        }
        if (!handler.validate(he.getRequestHeaders(), path)) {
            he.getResponseHeaders().set("WWW-Authenticate", "Basic realm=\"TurtleAPI\"");
            handler.sendResponse(he, 401, "{\"err\":\"Unauthorized\"}");
//            logger.log(Level.SEVERE, "Unauthorized");
            return;
        }
        try (OutputStream out = he.getResponseBody()) {
            try (InputStream in = he.getRequestBody()) {
                handler.handle(he, in, out, path);
            }
        }
    }
 
开发者ID:sherisaac,项目名称:TurteTracker_APIServer,代码行数:19,代码来源:RequestRegistry.java

示例3: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
	public void handle(HttpExchange t) throws IOException {

		// retrieve the request json data
		InputStream is = t.getRequestBody();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len;
		while ((len = is.read(buffer))>0) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		String data = new String(bos.toByteArray(), Charset.forName("UTF-8"));
		logit("Request: \n    " + data);

		// pass the data to the handler and receive a response
		String response = handler.handleRequest(data);
		logit("    " + response);
		
		// format and return the response to the user
		t.sendResponseHeaders(200, response.getBytes(Charset.forName("UTF-8")).length);
//		t.getResponseHeaders().set("Content-Type", "application/json");
		t.getResponseHeaders().set("Content-Type", "application/json, charset=UTF-8");
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes(Charset.forName("UTF-8")));
		os.close();
	}
 
开发者ID:SimplifiedLogic,项目名称:creoson,代码行数:28,代码来源:JshellHttpHandler.java

示例4: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange exchange) throws IOException {
    InputStream inputStream = exchange.getRequestBody();
    String query;
    String response;
    try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        query = scanner.useDelimiter("\\A").next();
        logger.info("Query: " + query);
        inputStream.close();
        response = queryServer(query, ReturnType.JSON);
    } catch (Exception e) {
        logger.info("ERROR", e);
        response = new Message("ERROR: " + e.getMessage(), true).toJson().toString();
    }

    // Add the header to avoid error:
    // “No 'Access-Control-Allow-Origin' header is present on the requested resource”
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.add("Access-Control-Allow-Origin", "*");
    exchange.sendResponseHeaders(200, response.length());

    OutputStream outputStream = exchange.getResponseBody();
    outputStream.write(response.getBytes());
    outputStream.close();
}
 
开发者ID:graphflow,项目名称:graphflow,代码行数:26,代码来源:PlanViewerHttpServer.java

示例5: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@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();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:Deadlock.java

示例6: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange exchange) throws IOException {
  String requestBody;
  try (BufferedReader br = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), "utf-8"))) {
    requestBody = br.lines().collect(Collectors.joining(System.lineSeparator()));
  }
  System.out.println("[x] Received body: \n" + requestBody);

  String response = "Hello from demo client!";
  exchange.sendResponseHeaders(200, response.length());
  System.out.println("[x] Sending response: \n" + response);

  OutputStream os = exchange.getResponseBody();
  os.write(response.getBytes());
  os.close();
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:17,代码来源:RestApiCallDemoClient.java

示例7: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public synchronized void handle (HttpExchange t)
    throws IOException
{
    byte[] buf = new byte[2048];
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }

    Headers map = t.getResponseHeaders();
    String redirect = root + "/foo/" + Integer.toString(count);
    increment();
    map.add("Location", redirect);
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:SmokeTest.java

示例8: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
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;
        }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:B6401598.java

示例9: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@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;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:BasicAuthTest.java

示例10: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:InfiniteLoop.java

示例11: main

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
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");
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:34,代码来源:ClassLoad.java

示例12: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
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();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:40,代码来源:Basic.java

示例13: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
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();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:15,代码来源:BasicLongCredentials.java

示例14: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
@Override
public void handle(HttpExchange t) throws IOException {
    try {
        InputStream is = t.getRequestBody();
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        String theString = writer.toString();

        List<NameValuePair> params = URLEncodedUtils.parse(theString, Charset.forName("UTF-8"));

        IridiumMessage message = new IridiumMessage(params);

        logger.debug(message);

        if (message.data == null || message.data.isEmpty()) {
            logger.info(MessageFormat.format("Empty MO message received ''{0}''.", message.toString()));
        } else if (message.imei.equalsIgnoreCase(imei)) {
            MAVLinkPacket packet = message.getPacket();

            if (packet != null) {
                MAVLinkLogger.log(Level.INFO, "MO", packet);

                dst.sendMessage(packet);
            } else {
                logger.warn(MessageFormat.format("Invalid MAVLink message ''{0}''.", message.toString()));
            }
        } else {
            logger.warn(MessageFormat.format("Invalid IMEI ''{0}''.", message.imei));
        }

        //Send response
        String response = "";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    } catch (DecoderException e) {
        logger.error(e.getMessage());
        throw new IOException(e.getMessage());
    }
}
 
开发者ID:envirover,项目名称:SPLGroundControl,代码行数:42,代码来源:RockBlockHttpHandler.java

示例15: handle

import com.sun.net.httpserver.HttpExchange; //导入方法依赖的package包/类
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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:54,代码来源:SimpleHttpServer.java


注:本文中的com.sun.net.httpserver.HttpExchange.getRequestBody方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。