【发布时间】:2013-05-22 05:53:39
【问题描述】:
我尝试了很多使用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 发送。
【问题讨论】:
-
所有这些向服务器发送 json 字符串的方法遇到了什么问题?
-
感谢 chintan,我看到了您的回答,我需要将您的第一种和第二种方式结合起来,但是如何?我没有得到。
-
感谢 ρяσѕρєя K,问题是:我可以将简单的字符串或 json 编码数据发布到服务器,但无法像在我的服务 url 中一样发布两者。