简体   繁体   中英

Setting parameters in HTTP POST

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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