2

我目前正在开发一个需要发送发布请求并从服务器获取 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”变量始终为空。不知道我做错了什么。

4

4 回答 4

1

这不应该是这样吗

HttpResponse httpResponse = httpClient.execute(httpPost);

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

如果服务器返回 JSONString..

say JSONObject data = new JSONObject(resp);

然后获取值..

于 2012-04-25T06:58:21.780 回答
0

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

于 2012-04-25T07:18:26.160 回答
0
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof  (List<NameValuePair> ));

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

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

并再次反序列化你得到的响应

于 2012-04-25T07:06:47.860 回答
0

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

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

所以感谢大家的回答。高度赞赏。

于 2012-04-26T04:43:23.113 回答