【问题标题】:HttpPost response doesn't return the json objectHttpPost 响应不返回 json 对象
【发布时间】:2012-04-25 06:55:11
【问题描述】:

我目前正在处理一个需要发送发布请求并从服务器获取 json 对象的项目。之前我使用 Get 方法来访问 json 对象。它工作得很好。但是由于一些服务器更改,我不得不转向发布方法。然后它不会返回我之前从“get”方法获得的 json 对象。我尽力想出一个解决方案,但不能。非常感谢有人能帮助我解决这个问题。

private AdSniperAdObjectResponse postData(String url) {
    //Bundle b = new Bundle();
    HttpClient httpClient = HttpClientFactory.getThreadSafeClient();
    //Log.d(TAG, "url: " + url);
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept", "JSON");


        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
        nameValuePairs.add(new BasicNameValuePair("latitude", "-33.8736"));
        nameValuePairs.add(new BasicNameValuePair("longitude", "151.207"));
        nameValuePairs.add(new BasicNameValuePair("age", "35"));
        nameValuePairs.add(new BasicNameValuePair("gender", "All"));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity resEntity = httpResponse.getEntity();
        if (resEntity != null) {
            String resp = EntityUtils.toString(resEntity);

上面是我使用的代码。早些时候我使用了 HttpGet 类。对于 HttpPost,“resp”变量始终为空。不知道我做错了什么。

【问题讨论】:

  • 我发现响应的状态码是400。这意味着请求有问题..

标签: java android json http-post http-get


【解决方案1】:

不应该这样吗

HttpResponse httpResponse = httpClient.execute(httpPost);

        if (httpResponse  != null) {
            String resp = httpResponse.toString();

如果服务器返回 JSONString..

say JSONObject data = new JSONObject(resp);

然后获取值..

【讨论】:

  • @Sandy..no sandy..它仍然给我一个空值。
【解决方案2】:
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof  (List<NameValuePair> ));

试试这个并使用这个传递你的数据

jsonSerializer.WriteObject(reqStream, nameValuePairs );
                reqStream.Close();

无论你得到什么,再次反序列化响应

【讨论】:

  • 问题是,在它进入 json 部分之前,当我尝试将 httpResponse 转换为字符串时,它给了我一个空值。如果我可以从响应中获取 json 字符串,其他部分就可以了..btw 谢谢
【解决方案3】:

在尝试获取HttpEntity 之前,您应该获取StatusLine 并检查状态代码是否符合您的预期。我怀疑真正的问题是服务器正在发送某种错误响应。而且由于您使用“Accept”标头来请求 JSON 响应,因此服务器可能没有在响应正文中发送任何诊断信息......所以它是空的。

【讨论】:

  • ..你知道如何检查httppost响应的状态行
【解决方案4】:

伙计们,我找到了解决方案。当我评论以下两行时,它起作用了。

httpPost.setHeader("Content-Type", "application/json");
    httpPost.setHeader("Accept", "JSON");

感谢大家的回答。非常感谢。

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多