3

I am new to Java and to client- server programming.

I am using embedded Jetty, and I'm trying to send a JSON string to some address (http://localhost:7070/json) and then to display the JSON string in that address.

I tried the following code but all I get is null.

Embedded Jetty code:

public static void main(String[] args) throws Exception {
    Server server = new Server(7070);
    ServletContextHandler handler = new ServletContextHandler(server, "/json");
    handler.addServlet(ExampleServlet.class, "/");
    server.start();
}

Client side function for sending the Http POST:

public static void sendHttp(){
    HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 

    try {
        HttpPost request = new HttpPost("http://localhost:7070/json");

        JSONObject object = new JSONObject();
        try {
            object.put("name", "MyName");
            object.put("age", "26");
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
        }

        String message = object.toString();
        request.setEntity(new StringEntity(message, "UTF8"));
        request.setHeader("Content-type", "application/json");

        HttpResponse response = httpClient.execute(request);

        // handle response here...
    }catch (Exception ex) {
        // handle exception here
    } finally {
    }
}

And Servlet functions:

public class ExampleServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //System.out.println("test get\n");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //System.out.println("test post\n");
        PrintWriter out = resp.getWriter();
        String json_str = req.getParameter("name");
        out.print(json_str);
    }
}

I call the sendHttp() method from a test class, after running the embedded Jetty server code (if that matters).

1

4 Answers 4

2

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

String data = IOUtils.toString(req.getInputStream(), "UTF-8");
Sign up to request clarification or add additional context in comments.

1 Comment

Check if you have import org.apache.commons.io.IOUtils;
2

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.

3 Comments

not sure I got it - do I need to change request.setHeader("Content-type", "application/json"); to request.setHeader("Content-type", "application/x-www-form-urlencoded");?
No you follow the first method. That is using req.getReader(). I put Note as an additional info.
fromObject(jb.toString() Whyare you trying to make a JSONObject from an object then calling a string? Also jb is not defined. 10/10 for effort.
2

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.....

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.