使用JSON对象作为数据的HTTP POST请求 - 我这样做是否正确?

时间:2014-10-13 18:56:07

标签: json http post request

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

如下所示,首先我创建了一个HTTP Post请求。然后我注释掉了它的一部分并尝试修改它以添加与JSON相关的代码。

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

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

}

0 个答案:

没有答案