This is my controller code:
@RequestMapping(value = "/test", method = RequestMethod.POST)
public @ResponseBody String testPost(@RequestParam(value = "testParam") int testParam, HttpServletRequest request) {
try {
System.out.println("body is "+BufferUtil.getHttpRequestBody(request));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
BufferUtil.getHttpRequestBody(request)
is
public static String getHttpRequestBody(HttpServletRequest request)
throws IOException {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8")
.useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
This is the code to use to test controller:
HTTPUtil.sendRequest("http://localhost:8081/es09android/test?testParam=1", "POST", "hello world");
sendRequest()
implementation:
public static HttpResponse sendRequest(String url, String method,
String data) {
DataOutputStream wr = null;
BufferedReader in = null;
HttpResponse httpResponse = new HttpResponse();
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod(method);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
if (data != null) {
wr = new DataOutputStream(con.getOutputStream());
wr.write(data.getBytes(UTF8_CHARSET));
}
int responseCode = con.getResponseCode();
httpResponse.setResponseCode(responseCode);
if (httpResponse.isOk()) {
in = new BufferedReader(new InputStreamReader(
con.getInputStream(), "UTF8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
httpResponse.setData(response.toString());
}
return httpResponse;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (wr != null) {
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If I run it and then send request, controller will not print body. But if remove @RequestParam(value = "testParam")
from the controller, everything will be ok. What is wrong?