繁体   English   中英

在HTTP POST中设置参数

[英]Setting parameters in HTTP POST

我正在尝试使用HttpClient API对服务器进行JSON调用。 代码sinppet如下所示。

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpPost(URLString);
HttpResponse response = httpClient.execute(httpPost);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
nameValuePairs.add(new BasicNameValuePair("method", "completeUserLogin")); 
String[] params = new String[]{"100408"};
response = httpClient.execute(httpPost);

我想将参数添加到nameValuePairs。 BasicNameValuePair类不允许您添加数组。 有什么想法吗?

提前致谢!

看这个 。 它们在BasicNameValuePairs中传递数组。这里的颜色是我们要在服务器上发送的数组。 您应该使用数组变量而不是颜色。

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
nameValuePairs.add(new BasicNameValuePair("colours[0]","red"));  
nameValuePairs.add(new BasicNameValuePair("colours[1]","white"));  
nameValuePairs.add(new BasicNameValuePair("colours[2]","black"));  
nameValuePairs.add(new BasicNameValuePair("colours[3]","brown"));  

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);

如果您以json格式发布数据,则不应发布此类参数。 而是创建一个JSONObject,将这些值放在该json对象中,并从该json对象获取一个字符串,然后创建一个StringEntity,并将此Entity设置为HttpPost对象。

为请求创建JSONObject:

JSONObject json=new JSONObject();
json.put("method", "completeUserLogin");
JSONArray arr= new JSONArray();
arr.put("100408");
json.put("params", arr);

String params=json.toString();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM