7

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Joshua
  • 151
  • 1
  • 1
  • 9

5 Answers5

6
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()
Perception
  • 79,279
  • 19
  • 185
  • 195
Joshua
  • 151
  • 1
  • 1
  • 9
4

If you are using Spring MVC, you can use the @RequestBody annotation on a method parameter which is of type String. For example.

@RequestMapping(value = "/something", method = RequestMethod.POST)
public void doSomething(@RequestBody String requestBodyString) {
    // does something..
}
Suketu Bhuta
  • 1,871
  • 1
  • 18
  • 26
1

You can use Commons IO's org.apache.commons.io.IOUtils.toString(InputStream, String) to do this in one line. (It might not work with HTTP keep-alive though)

Edit:

If you want to go straight to JSON, there are a bunch of Web Service stacks that will do the unmarshalling for you. Try

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

artbristol
  • 32,010
  • 5
  • 70
  • 103
0

Did you try this ?

 InputStreamReader isr =  new InputStreamReader(exchange.getRequestBody(),"utf-8");
 BufferedReader br = new BufferedReader(isr);
 String value = br.readLine();
Sunil
  • 1,238
  • 3
  • 13
  • 21
  • Yes, I tried. The problem is that the body does not end with CR/LF. I found a solution by using the read(char[]) method with the content-length and it approximately works. I wonder if it is not a method that performs this reading job to the end. – Joshua May 01 '12 at 05:37
  • You should get the encoding from the HTTP headers, not just assume it's UTF-8. – artbristol May 01 '12 at 07:53
0

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());
Dharman
  • 30,962
  • 25
  • 85
  • 135