这是我向服务器发送 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 在这里提供的类(class) Send HTTPS Post Request to the server
我正在获取响应对象。但是我的 response.getStatusLine() 一直显示 500/Internal server error for only POST requests.
注意: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。
最佳答案
我认为你应该设置 contentType: "application/json"
可能会有帮助,请试试这个。
谢谢
关于android - 500 内部服务器错误与 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14065236/