Send Array of objects using HttpPost in Android - java

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"}]"));

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

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

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

Related

java client send Json as parameter or request body

I would like to send a json string using httpost(apache). I have two ways to do it.
I can make it as a parameter like this :
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("json",myJsonString));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
or I can make it as request body:
StringEntity params =new StringEntity(myJsonString);
request.addHeader("content-type", "application/json");
request.setEntity(params);
Which way I should do if myJsonString is very large? I'm using the 1st way because in servlet I just need to read it as a parameter.

send just a string with http Post but error

Sorry, I don't speak English very well.
I try to send string "Nhập nội dung bình luận để gửi đi!".
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
String str ="Nhập nội dung bình luận để gửi đi!";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("file", str));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
But I get "Nhập nội dung bình l" on my web server. How can I resolve it.
EDIT:
I encoded to UTF-8 by this code:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
replace by:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
but it still doesn't work.
Try this change:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
The server must also be able to handle UTF-8 for that to work.
Alternatively, if the text will be rendered as HTML, you can encode the whole thing so the server doesn't need to support UTF-8.
String str ="Nhập nội dung bình luận để gửi đi!";
That's html encoding, not URL encoding. Unfortunately Java doesn't include an html encoder as far as I know. You'd have to use a 3rd party library.
This thread lists a few libraries:
Is there a JDK class to do HTML encoding (but not URL encoding)?
Full hack using an example from that other thread. Try something like this...
public void post() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
String str ="Nhập nội dung bình luận để gửi đi!";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("file", encodeHTML(str)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
public static String encodeHTML(String s)
{
StringBuffer out = new StringBuffer();
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if(c > 127 || c=='"' || c=='<' || c=='>')
{
out.append("&#"+(int)c+";");
}
else
{
out.append(c);
}
}
return out.toString();
}
You need to encode the String with appropriate charset before sending to the web server. Otherwise, the String will be encoded in the default charset of the platform used. Check whether both server and program are using the correct charset to write and read the String
Say for example, it is UTF-8, Create String from ByteArray encoded with UTF-8 charset with code below
new String(YOUR_BYTE_ARRAY, Charset.forName("UTF-8"));
Reading the encoded String into ByteArray with same charset UTF-8 on the server side can be done as follows
YOUR_UTF8_STRING.getBytes("UTF-8");
Hope this clarifies!
Encode your url when sending from application:
// import java.net.URLEncoder;
str = URLEncoder.encode(str, "UTF-8");
And from the receiver decode the string:
// import java.net.URLDecoder;
str = URLDecoder.decode(str, "UTF-8");

UrlEncodedFormEntity equivalent in javascript

In java while doing an HTTP post request using nameValuePairs we write the following code!
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sometesturl.com");
JSONObject json = new JSONObject();
json.put("id",1);
json.put("name","john");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", "abc"));
nameValuePairs.add(new BasicNameValuePair("samplejson", json.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
As seen over here we use the UrlEncodedFormEntity to encode our request body. Similarly, I need to do the same in Javascript. I have seen the EncodeURIComponent method but that doesn't seem to encode the request body. Instead it encodes the URL.
Can someone tell me how to encode the request body in javascript?

Java passing multidimensional array to PHP

I tryied to find some information about this but is a bit difficult since all i found is about javascript instead of java,
I want to know how i can get it in php too because i m not sure how to do it
I am trying to pass an array multidimensional by post, i have no idea how to pass a multdimensional array by java this is my code(i suppose that i only will need to change a few)
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://web");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (int count=0; count < array.length; count++)
{//this loop is what i need to change but i dont know how to do it
nameValuePairs.add(new BasicNameValuePair("foto",array[count][0]));
nameValuePairs.add(new BasicNameValuePair("media",array[count][1]));
nameValuePairs.add(new BasicNameValuePair("votos",array[count][2]));
}
if(nameValuePairs != null) httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.execute(httppost, responseHandler);
}
I think you should serialize the data to JSON/XML/CSV format and parse it on the server side. Otherwise it will be not so intelligent code.

Sending integer value using DefaultHttpClient

I am using DefaultHttpClient to send data to web... To send data m using following code block:
nameValuePairs.add(new BasicNameValuePair(name, value));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
but namevaluepairs only take string.. I need to send integer value with this.
Please guide..
Thanks in advance.
Use Integer.toString(integerValue). For example:
nameValuePairs.add(new BasicNameValuePair(name, Integer.toString(5)));
Edit, further to the comments below:And for a float you can use:
nameValuePairs.add(new BasicNameValuePair(name, Float.toString(10.82522f)));

Categories