【问题标题】:500 Internal Server Error with POST RequestsPOST 请求出现 500 内部服务器错误
【发布时间】:2016-09-19 15:58:01
【问题描述】:

这是我对服务器的 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 Here Send HTTPS Post Request to the server 提供的课程@

我正在获取响应对象。但我的 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。

【问题讨论】:

  • 最好使用httpurlconnection 而不是HttpPostHttpGet 来执行任何与服务器相关的任务
  • 感谢发布解决方案

标签: android


【解决方案1】:

我认为你应该设置contentType: "application/json" 可能会有所帮助,请试试这个。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多