使用JSON对象作为数据的HTTP POST请求

时间:2014-10-13 16:46:39

标签: java json http post

我正在努力用JSON对象作为数据发出HTTP POST请求。

如下所示,首先我创建了一个HTTP Post请求。然后我注释掉了它的一部分并尝试修改它以添加与JSON相关的代码。令我感到困惑的一件事是,尽管看到许多使用导入“org.json.simple.JSONObject”的教程,但我的IDE会读取错误消息并指出“导入org.json.simple.JSONObject无法解析”。

有关如何使此代码正常工作的任何建议都将非常感激。

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

3 个答案:

答案 0 :(得分:1)

IDE说它无法解析导入org.json.simple.JSONObject的原因是因为org.json.simple.*包和类不包含在Java中,而是属于JSON Simple library

答案 1 :(得分:1)

我认为使用Socket并不是一个好主意。你可以更好地使用:

http://hc.apache.org/httpcomponents-client-ga/(HTTP客户端)

或java.net.URLConnection。例如:

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

答案 2 :(得分:0)

你需要带有org.json.simple.JSONObject实现的jar: http://www.java2s.com/Code/Jar/j/Downloadjsonsimple11jar.htm