这是我向服务器发出 POST 请求的代码。
要发布到服务器的 JSON :
{
"User": {
"Name": "dog","Password": "123" }
}
Run Code Online (Sandbox Code Playgroud)
我如何创建 JSON 对象
object = new JSONObject();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Name", "dog");
jsonObject.put("Password", "123");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
object.put("User", jsonObject);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
发布到服务器作为
public HttpResponse request(JSONObject request)
throws ClientProtocolException, IOException, IllegalStateException,
JSONException {
client = (DefaultHttpClient) WebClientDevWrapper
.getNewHttpClient();
HttpPost post = new HttpPost(
"https://wbapi.cloudapp.net:443/api/User/LocalLogin/");
post.setEntity(new StringEntity(request.toString(), "utf-8"));
HttpResponse response = client.execute(post);
return response;
}
Run Code Online (Sandbox Code Playgroud)
连同 Paresh Mayani 提供的类,这里将 HTTPS Post 请求发送到服务器
我正在获取响应对象。但是我的 response.getStatusLine() 一直显示 500/ 仅 POST 请求的内部服务器错误。
注意:GET 请求工作正常。
我的代码有什么问题?我该如何解决这个错误?
将请求代码更改为(根据 Bhavdip Pathar 的建议)
public HttpResponse request(JSONObject request)
throws ClientProtocolException, IOException, IllegalStateException,
JSONException {
HttpPost post = new HttpPost(
"https://wbapi.cloudapp.net:443/api/User/LocalLogin/");
// post.setEntity(new StringEntity(request.toString(), "utf-8"));
StringEntity entity = new StringEntity(request.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
post.setEntity(entity);
HttpResponse response = client.execute(post);
return response;
}
Run Code Online (Sandbox Code Playgroud)
我确实设置了 application/json 和 voila ,我得到 HTTP/200 OK。
| 归档时间: |
|
| 查看次数: |
20776 次 |
| 最近记录: |