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).
To get the data from a Post request you need to obtain the content. Try this:
String data = IOUtils.toString(req.getInputStream(), "UTF-8");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With