使用Java将数据发布到服务器,例如jQuery的$ .post()

时间:2014-08-20 17:41:32

标签: java post httpurlconnection

我有一个网络后端,使用以下jQuery帖子:

$.post(path + "login",
       {"params": {"mode":"self", "username": "aaa", "password": "bbb"}},
       function(data){
                console.log(data);
            }, "json");

如何使用HttpURLConnection从Java实现相同的POST?我正在尝试

URL url = new URL(serverUrl + loginUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length",
    Integer.toString(postData.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr =
    new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(postData);
wr.flush ();
wr.close ();
BufferedReader br =
    new BufferedReader(
        new InputStreamReader(connection.getInputStream()));

,其中postData = "{\"mode\": \"...\", ..... }"

但它的工作方式不同。

服务器上的代码写为id Django,并尝试以这种方式获取数据:

mode=request.POST.get("params[mode]")

2 个答案:

答案 0 :(得分:1)

您似乎一直在考虑jQuery以原始形式将JSON发送到服务器,并且HTTP服务器完美地理解它。这不是真的。 HTTP请求参数的默认格式为application/x-www-form-urlencoded,与HTTP网站中的HTML表单使用的格式完全相同,与URL中的GET查询字符串的外观完全相同:name1=value1&name2=value2

换句话说,jQuery不会将未经修改的JSON发送到服务器。 jQuery只是透明地将它们转换为真正的请求参数。在理智的浏览器中按F12并检查HTTP流量监视器也应该向您显示。您在"json"末尾指定的$.post参数只是告诉jQuery服务器返回的数据格式(因此不是它消耗的数据格式)。

所以,就像jQuery在幕后做的一样:

String charset = "UTF-8";
String mode = "self";
String username = "username";
String password = "bbb";
String query = String.format("%s=%s&%s=%s&%s=%s",
    URLEncoder.encode("param[mode]", charset), URLEncoder.encode(mode, charset),
    URLEncoder.encode("param[username]", charset), URLEncoder.encode(username, charset),
    URLEncoder.encode("param[password]", charset), URLEncoder.encode(password, charset));

// ... Now create URLConnection.

connection.setDoOutput(true); // Already implicitly sets method to POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

try (OutputStream output = connection.getOutputStream()) {
    output.write(query.getBytes(charset));
}

// ... Now read InputStream.

注意:请勿使用Data(Input|Output)Stream!这些是用于创建/阅读.dat文件。

另见:

答案 1 :(得分:-1)

您应该使用高效的库来构建(有效的)json对象。以下是PrimeFaces库中的一个示例:

private JSONObject createObject() throws JSONException {
    JSONObject object = new JSONObject();
    object.append("mode", "...");
    return object;
}

如果您希望有一个漂亮而干净的代码来发送和检索对象,请查看Emil Adz(Sending Complex JSON Object)的答案。

相关问题