Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http Post With Body

Tags:

java

android

i have sent method in objective-c of sending http post and in the body i put a string:

NSString *requestBody = [NSString stringWithFormat:@"mystring"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]];

now in Android i want to do the same thing and i am looking for a way to set the body of http post.

like image 542
YosiFZ Avatar asked Jul 21 '11 14:07

YosiFZ


2 Answers

You can use HttpClient and HttpPost to build and send the request.

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));

request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
like image 196
JustDanyul Avatar answered Sep 18 '22 12:09

JustDanyul


You could use this snippet -

HttpURLConnection urlConn;
URL mUrl = new URL(url);
urlConn = (HttpURLConnection) mUrl.openConnection();
...
//query is your body
urlConn.addRequestProperty("Content-Type", "application/" + "POST");
if (query != null) {
urlConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
urlConn.getOutputStream().write(query.getBytes("UTF8"));
}
like image 25
Suchi Avatar answered Sep 19 '22 12:09

Suchi