Renjith
Renjith

Reputation: 3617

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!

Upvotes: 0

Views: 8889

Answers (2)

jeet
jeet

Reputation: 29199

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

Upvotes: 1

Chirag
Chirag

Reputation: 56935

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

Upvotes: 7

Related Questions