Java 在HTTP POST中设置参数

Java 在HTTP POST中设置参数,java,android,http,Java,Android,Http,我正在尝试使用HttpClient API对服务器进行JSON调用。代码sinppet如下所示 HttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpPost(URLString); HttpResponse response = httpClient.execute(httpPost); List<NameValuePair> nameValuePairs = new ArrayLis

我正在尝试使用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);
HttpClient-HttpClient=newdefaulthttpclient();
HttpGet-httpPost=新的httpPost(URLString);
HttpResponse response=httpClient.execute(httpPost);
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“方法”,“完成登录”);
字符串[]参数=新字符串[]{“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);
List nameValuePairs=new ArrayList();
添加(新的BasicNameValuePair(“颜色[0],“红色”));
nameValuePairs.add(新的BasicNameValuePairs(“颜色[1],“白色”));
添加(新的BasicNameValuePair(“颜色[2]”,黑色”);
添加(新的BasicNameValuePair(“颜色[3],“棕色”);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
response=httpClient.execute(httpPost);

如果您以json格式发布数据,则不应像这样发布参数。而是创建一个JSONObject,将这些值放入该json对象中,从该json对象中获取一个字符串,然后创建一个StringEntity,并将该实体设置为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();

您应该尝试将数组转换为文章所期望的字符串表示形式,然后添加它。您知道吗,请参见jeet的答案。:)