如何在服务器端将HTTP POST请求主体作为Java String? [英] How to get a HTTP POST request body as a Java String at the server side?

查看:223
本文介绍了如何在服务器端将HTTP POST请求主体作为Java String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpExchange对象的getRequestBody方法返回一个InputStream。正确阅读身体还有很多工作要做。它是一个Java库+对象+方法再向前一步并将正文(在服务器端)作为即用型Java字符串返回吗?

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 String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆