HttpPost响应不返回json对象

时间:2012-04-25 06:55:11

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

我目前正在开发一个需要发送post请求并从服务器获取json对象的项目。之前我使用Get方法访问json对象。它工作正常。但由于一些服务器的更改,我不得不转向post方法。然后它不会返回我之前从'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'变量始终为null。不知道我做错了什么。

4 个答案:

答案 0 :(得分:1)

不应该像

HttpResponse httpResponse = httpClient.execute(httpPost);

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

如果服务器返回JSONString ..

say JSONObject data = new JSONObject(resp);

然后获取值..

答案 1 :(得分:0)

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof  (List<NameValuePair> ));

尝试使用此功能并使用此

传递数据
jsonSerializer.WriteObject(reqStream, nameValuePairs );
                reqStream.Close();
无论你得到什么,

再次反序列化响应

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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

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

相关问题