在android中使用HttpPost发布JsonArray和字符串参数

时间:2013-05-22 05:53:40

标签: android json http-post

我尝试了很多方法使用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 ---&GT;

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发送的。

1 个答案:

答案 0 :(得分:3)

  

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

=&GT;是的,显而易见的是,您的Web服务URL遵循GET方法,而不是POST。

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

因此,我建议您尝试HTTPGet方法,而不是HTTPPost

查看adding parameters to a HTTP GET request in Android的答案?