0

I have an app that sends an object to an api via HttpPost. I have some sample such:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Destination", destination));
nameValuePairs.add(new BasicNameValuePair("Description", description));
nameValuePairs.add(new BasicNameValuePair("CreatorName ", myName));

In this object, I have an array of "User" objects, which has a DisplayName and Phone. How can I send this array through HttpPost? The following is not recognized by the server (where the quotes are escaped):

nameValuePairs.add(new BasicNameValuePair("Users", "[{"Destination":"St.Louis", "Phone":"1234"}]"));

3
  • "where the quotes are escaped ?" what do you mean? Commented Feb 6, 2015 at 3:44
  • Sorry, I mean that in the actual code it looks like this: nameValuePairs.add(new BasicNameValuePair("Users", "[{"\"Destination\"":"\"St.Louis\"", "\"Phone\"":"\"1234\""}]")); Commented Feb 6, 2015 at 3:54
  • try read this one. Commented Feb 6, 2015 at 3:58

3 Answers 3

1

Simplest way is to convert the Array as String (or JSON string). Then encode it with your server after passing as entity.

Sign up to request clarification or add additional context in comments.

Comments

1

try this

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);

StringEntity se = new StringEntity(nameValuePairs.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);

Comments

0

I think this code should work.

nameValuePairs.add(new BasicNameValuePair("user[0]", gson.toJson(users.get(0))));
nameValuePairs.add(new BasicNameValuePair("user[1]", gson.toJson(users.get(1))));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.