[英]How to get a HTTP POST request body as a Java String at the server side?
HttpExchange對象的getRequestBody方法返回一個InputStream。 正確閱讀“身體”還有很多工作要做。 它是一個Java庫+對象+方法又領先一步並將正文(在服務器端)作為即用型Java字符串返回?
謝謝!
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()
如果您使用的是Spring MVC,則可以對類型為String的方法參數使用@RequestBody批注。 例如。
@RequestMapping(value = "/something", method = RequestMethod.POST)
public void doSomething(@RequestBody String requestBodyString) {
// does something..
}
您可以使用Commons IO的org.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
你試過這個嗎?
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String value = br.readLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.