How to get the body of an HTTP POST request as a Java string on the server side?

The getRequestBody method of the HttpExchange object returns an InputStream. There is still a lot of work to properly read The Body. Is it a Java library + object + method that takes it one step further and returns the body (server side) as a ready-to-use Java string?

+4
source share
5 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()
+4
source

If you use Spring MVC, you can use the @RequestBody annotation for a method parameter that is of type String. For instance.

@RequestMapping(value = "/something", method = RequestMethod.POST)
public void doSomething(@RequestBody String requestBodyString) {
    // does something..
}
+3
source

Commons IO org.apache.commons.io.IOUtils.toString(InputStream, String), . (, HTTP keep-alive)

Edit:

JSON, -, unmarshalling.

Spring: 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

+1
source

Have you tried this?

 InputStreamReader isr =  new InputStreamReader(exchange.getRequestBody(),"utf-8");
 BufferedReader br = new BufferedReader(isr);
 String value = br.readLine();
0
source

In 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());
0
source

All Articles