这是我对服务器的 POST 请求的代码。
要发布到服务器的 JSON:
{
"User": {
"Name": "dog","Password": "123" }
}
我如何创建 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();
}
发布到服务器作为
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;
}
连同 Paresh Mayani 提供的类在这里向服务器发送 HTTPS 发布请求
我得到响应对象。但是我的 response.getStatusLine() 仅针对 POST 请求一直显示 500/ Internal server error。
注意: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;
}
我确实设置了 application/json 和瞧,我得到了 HTTP/200 OK。