HTTP POST request with JSON object as data

2019-08-06 19:16发布

问题:

I am struggling to make an HTTP POST request with JSON object as data.

As you can see below, first I created an HTTP Post request. Then I commented out part of it and attempted to modify it in order to add JSON related code. One of the things that confused me was that despite seeing a number of tutorials using the import "org.json.simple.JSONObject" my IDE reads an error message and states "the import org.json.simple.JSONObject cannot be resolved".

Any advice about how to make this code work would be much appreciated.

 import java.io.*;
 import java.net.*;
 import org.json.simple.JSONObject;

 public class HTTPPostRequestWithSocket {

    public void sendRequest(){

        try {

            JSONObject obj = new JSONObject();
            obj.put("instructorName", "Smith");
            obj.put("courseName", "Biology 101");
            obj.put("studentName1", "John Doe");
            obj.put("studentNumber", new Integer(100));
            obj.put("assignment1", "Test 1");
            obj.put("gradeAssignment1", new Double("95.3"));

           /*
           //Note that this code was taken out in order to attempt to send
           //the information in the form of JSON.
           String params = URLEncoder.encode("param1", "UTF-8")
                + "=" + URLEncoder.encode("value1", "UTF-8");
            params += "&" + URLEncoder.encode("param2", "UTF-8")
                + "=" + URLEncoder.encode("value2", "UTF-8");
             */

            String hostname = "nameofthewebsite.com";
            int port = 80;

            InetAddress addr = InetAddress.getByName(hostname);
            Socket socket = new Socket(addr, port);
            String path = "/nameofapp";

            // Send headers
            BufferedWriter wr = new BufferedWriter(new     
            OutputStreamWriter(socket.getOutputStream(), "UTF8"));
            wr.write("POST "+path+" HTTP/1.0rn");
            wr.write("Content-Length: "+obj.length()+"rn");
            wr.write("Content-Type: application/x-www-form-urlencodedrn");
            wr.write("rn");

            // Send parameters
            wr.write(obj);
            wr.flush();

            // Get response
            BufferedReader rd = new BufferedReader(new   InputStreamReader(socket.getInputStream()));
             String line;

            while ((line = rd.readLine()) != null) {
                System.out.println(line);
                }

            wr.close();
            rd.close();
            socket.close();//Should this be closed at this point?
            }catch (Exception e) {e.printStackTrace();}
        }
}

回答1:

The reason your IDE says it cannot resolve the import org.json.simple.JSONObject is because the org.json.simple.* packages and classes are not included in Java, but rather belong to the JSON Simple library.



回答2:

I think that uses Socket is not a good idea. You can better use:

http://hc.apache.org/httpcomponents-client-ga/ (A HTTP Client)

or a java.net.URLConnection. Example:

http://crunchify.com/create-very-simple-jersey-rest-service-and-send-json-data-from-java-client/



回答3:

You need the jar with the org.json.simple.JSONObject implementation: http://www.java2s.com/Code/Jar/j/Downloadjsonsimple11jar.htm