如何使用JSON发出HTTP POST请求?

时间:2014-10-11 21:36:56

标签: java json http post

我理解Java,但对连接到Web应用程序完全缺乏经验。我如何获取以下HTTP POST请求并使其成为JSON?总体目的是将信息从Java应用程序发送到在线Ruby on Rails SQLite3数据库。

import java.io.*;
import java.net.*;

public class HTTPPostRequestWithSocket {
    public void sendRequest() {
        try {
            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: " + params.length() + "rn");
            wr.write("Content-Type: application/x-www-form-urlencodedrn");
            wr.write("rn");

            // Send parameters
            wr.write(params);
            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 个答案:

没有答案