Setting parameters in HTTP POST

2019-09-12 05:56发布

问题:

I am trying make a JSON call to a server using HttpClient API. The code sinppet is shown below.

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);

I want to add params to nameValuePairs. BasicNameValuePair class does not allow you to add arrays. Any thoughts?

Thanks in advance!

回答1:

If you are posting data in json format then you should not post params like this. Instead create a JSONObject put these values in that json object, and get a string from that json object and then create a StringEntity, and set this Entity to HttpPost object.

Creating JSONObject for the Request:

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

String params=json.toString();


回答2:

Look at this . Here they pass the array in BasicNameValuePairs.Here the colours is the array which we are going to send on a server. You should use your array varible instead of colours.

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);