5

HttpExchange 对象的getRequestBody 方法返回一个InputStream。正确阅读“正文”还有很多工作要做。它是一个 Java 库 + 对象 + 方法,它更进一步并将主体(在服务器端)作为现成的 Java 字符串返回?

4

5 回答 5

6
InputStreamReader isr =  new InputStreamReader(t.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);

// From now on, the right way of moving from bytes to utf-8 characters:

int b;
StringBuilder buf = new StringBuilder(512);
while ((b = br.read()) != -1) {
    buf.append((char) b);
}

br.close();
isr.close();

// The resulting string is: buf.toString()
// and the number of BYTES (not utf-8 characters) from the body is: buf.length()
于 2012-06-06T07:36:22.900 回答
3

如果您使用的是 Spring MVC,则可以在 String 类型的方法参数上使用 @RequestBody 注释。例如。

@RequestMapping(value = "/something", method = RequestMethod.POST)
public void doSomething(@RequestBody String requestBodyString) {
    // does something..
}
于 2014-12-29T16:35:01.397 回答
1

你试过这个吗?

 InputStreamReader isr =  new InputStreamReader(exchange.getRequestBody(),"utf-8");
 BufferedReader br = new BufferedReader(isr);
 String value = br.readLine();
于 2012-05-01T05:32:19.677 回答
1

您可以使用 Commons IOorg.apache.commons.io.IOUtils.toString(InputStream, String)在一行中完成此操作。(虽然它可能不适用于 HTTP keep-alive)

编辑:

如果您想直接使用 JSON,有一堆 Web 服务堆栈可以为您进行解组。尝试

春天:http ://www.cribbstechnologies.com/2011/04/08/spring-mvc-ajax-web-services-part-2-attack-of-the-json-post/

CXF / JAX-RS:http ://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-JSONsupport

于 2012-05-01T07:55:29.650 回答
0

在 HttpHandler 中:

InputStreamReader isr = new InputStreamReader(he.getRequestBody(), "utf-8");
        BufferedReader br = new BufferedReader(isr);

        int b;
        StringBuilder buf = new StringBuilder();
        while ((b = br.read()) != -1) {
            buf.append((char) b);
        }

        br.close();
        isr.close();
System.out.println(buf.toString());
于 2019-09-17T21:59:47.923 回答