Read JSON message from HTTP POST request in Java

为君一笑 提交于 2019-12-06 14:56:45
Tom Sebastian

You need to read the raw request body as below. Put this inside your doPost method of servlet for reading json from the request:

StringBuilder jsonBuff = new StringBuilder();
String line = null;
try {
    BufferedReader reader = req.getReader();
    while ((line = reader.readLine()) != null)
        jsonBuff.append(line);
} catch (Exception e) { /*error*/ }

System.out.println("Request JSON string :" + jsonBuff.toString());
//write the response here by getting JSON from jasonBuff.toString()

try {
    JSONObject jsonObject = JSONObject.fromObject(jb.toString());

    out.print(jsonObject.get("name"));//writing output as you did

} catch (ParseException e) {
    throw new IOException("Error parsing JSON ");
}

Note : You can access req.getParameter("name"); only when your headers would be like this:

content type: "application/x-www-form-urlencoded"

as in normal html form submission.

To get the data from a Post request you need to obtain the content. Try this:

String data = IOUtils.toString(req.getInputStream(), "UTF-8");

I have not used jetty but I have done similar comunications with this code (PUT, not POST):

URL url = new URL(desturl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("PUT");
byte[] postData = null; 
int postDataLength; 
huc.setDoOutput(true);
postData = data.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
huc.setRequestProperty( "Content-Type", "application/json"); 
huc.setRequestProperty( "charset", "utf-8");
huc.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
huc.setUseCaches( false );
huc.connect();
huc.setConnectTimeout(10000);
DataOutputStream wr = new DataOutputStream( huc.getOutputStream());
wr.write( postData );
rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
retcode = huc.getResponseCode();

Here is my code this works fine

    String data = "";   
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    data = builder.toString();
    JSONObject object = new JSONObject(data); 
   //or JSONArray array = new JSONArray(data); which ever the one you want

Good luck.....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!