Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an HTTP POST request body as a Java String at the server side?

Tags:

java

http

post

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?

like image 554
Joshua Avatar asked May 01 '12 05:05

Joshua


1 Answers

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()
like image 77
Joshua Avatar answered Oct 11 '22 15:10

Joshua