【发布时间】:2014-08-20 17:41:32
【问题描述】:
我有一个 Web 后端,可以与以下 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]")
【问题讨论】:
-
什么意思不一样?你想让它做什么?它的作用是什么?
-
它将一些数据发布到网络服务器,我想以字符串形式获取响应。当我尝试将它与具有上述 jQuery 函数的 HTML 页面一起使用时,它可以工作。但我无法从 Java 重新创建相同的发布请求。
-
它返回 HTTPError 500,因为服务器上的代码无法从请求中获取数据,它想要...
标签: java post httpurlconnection