如何在服务器端获取HTTP POST请求正文作为Java字符串? [英] How to get an HTTP POST request body as a Java String at the server side?
本文介绍了如何在服务器端获取HTTP POST请求正文作为Java字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HttpExchange对象的getRequestBody方法返回一个InputStream.正确阅读正文"还有很多工作.是Java库+对象+方法又向前迈进了一步,并将主体(在服务器端)返回为现成的Java String吗?
The getRequestBody method of the HttpExchange object returns an InputStream. There is still much work for correctly read the "Body". Is it a Java library + object + method that goes one more step ahead and returns the body (at the server side) as a ready-to-use Java String?
推荐答案
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()
这篇关于如何在服务器端获取HTTP POST请求正文作为Java字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文