2

我尝试了很多方法来发送数据,HttpPost但我没有成功,如果有人知道这个请帮忙?

我的服务网址是:
http://xxxxx/xxx/abc.php?id=xx&name=xxx&data=[{.....}]

当我从浏览器点击但我的代码data=[{}]没有发送时,它工作正常。

我最后的尝试是:
1--->

String serviceUrl = "http://xxxxx/xxx/abc.php"; 


DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(serviceUrl);
        httpPost.setHeader("id", "xx");
        httpPost.setHeader("name", "xxx");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(jsonArr.toString(), HTTP.UTF_8);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        json_str = EntityUtils.toString(httpEntity);

2--->

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("id", "xx") );
    nameValuePairs.add(new BasicNameValuePair("name", "xxx"));      
    nameValuePairs.add(new BasicNameValuePair("data", jsonArr.toString()));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(serviceUrl);
        httpPost.setHeader("Content-Type", "application/json"); 
        StringEntity entity = new StringEntity(nameValuePairs.toString(), HTTP.UTF_8);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        json_str = EntityUtils.toString(httpEntity);

3--->

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "xx") );
nameValuePairs.add(new BasicNameValuePair("name", "xxx"));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serviceUrl);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));   
StringEntity entity = new StringEntity(jsonArr.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
json_str = EntityUtils.toString(httpEntity);

输出: 得到的响应与我在浏览器上使用 url(不带数据参数)得到的响应相同'http://xxxxx/xxx/abc.php?id=xx&name=xxx',我的意思是 data=[{}] 没有从我的代码中使用 simple_string_parameters 发送。

4

1 回答 1

3

尝试了很多使用 HttpPost 发送数据但没有成功的方法

=> 是的,因为您的 Web 服务 URL 遵循 GET 方法,而不是 POST,所以很明显。

http://xxxxx/xxx/abc.php?id=xx&name=xxx&data=[ {.....}]

所以我建议你尝试HTTPGet方法而不是HTTPPost.

检查此答案以在 Android 中向 HTTP GET 请求添加参数

于 2013-05-22T05:58:03.813 回答