HttpExchange对象的getRequestBody方法返回一个InputStream。正确阅读“身体”还有很多工作要做。它是一个Java库+对象+方法又领先一步并将主体(在服务器端)作为即用型Java字符串返回?
谢谢!
答案 0 :(得分:4)
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()
答案 1 :(得分:3)
如果您使用的是Spring MVC,则可以对类型为String的方法参数使用@RequestBody注释。例如。
@RequestMapping(value = "/something", method = RequestMethod.POST)
public void doSomething(@RequestBody String requestBodyString) {
// does something..
}
答案 2 :(得分:1)
您可以使用Commons IO的org.apache.commons.io.IOUtils.toString(InputStream, String)
在一行中执行此操作。 (虽然它可能不适用于HTTP keep-alive)
编辑:
如果你想直接使用JSON,有一堆Web服务堆栈可以为你进行解组。尝试
CXF / JAX-RS:http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-JSONsupport
答案 3 :(得分:0)
你试过这个吗?
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String value = br.readLine();
答案 4 :(得分: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());