HttpPost Posting Complex JSONObject in the Body of the Request - java

I was wondering, using HttpClient and HttpPOST is there a way to post a complex JSON object as the body of the request? I did see an example of posting a simple key/value pair in the body (as shown below from this link: Http Post With Body):
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);
However, I would need to post something like the following:
{
"value":
{
"id": "12345",
"type": "weird",
}
}
Is there a way for me to accomplish this?
ADDITIONAL INFORMATION
Doing the following:
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
results in an empty body on the server... hence i get a 400.
Thanks in advance!

HttpPost.setEntity() accepts StringEntity which extends AbstractHttpEntity. you can set it with any valid String of your choice:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);

This worked for me!
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);

Related

Unsupported grant type with API

I'm trying to get token from sever response it works great with postMan , but when debug it with android it gets error:
unsupported_grant_type
here is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(LoginURL);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
// post.setHeader("Accept", "application/x-www-form-urlencoded");
JSONObject obj = new JSONObject();
try {
obj.put("grant_type", "password");
obj.put("password", PasswordEditText);
obj.put("username", EmailEditText+"gfg");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
results = EntityUtils.toString(entity);
myObject = new JSONObject(results);
finally I have found the solution :
replace :
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
With:
post.setEntity(new StringEntity("grant_type=password&username=0000#gmail.com&password=00000", "UTF-8"));

Java HTTP Post form and file

So I want to use the TestFairy API (url: https://app.testfairy.com/api/upload). This API call expects 3 post paramters:
api_key (string)
apk_file (.apk file)
testers_groups (string)
So far I came up with this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("testers_groups", testers));
params.add(new BasicNameValuePair("api_key", key));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("apk_file", new FileBody(file));
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
But it does not work.
Can anybody point me in the right direction?
Try something like this:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("api_key", new StringBody(key));
entity.addPart("apk_file", new FileBody(file));
entity.addPart("testers_groups", new StringBody(testers));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
Optionally add mime-types in the StringBody and FileBody constructors (but probably not necessary).

USPS Tracking API

I am trying to use the USPS tracking API. When I send in a request to the production server, I get a 501 response code.
StringEntity se = new StringEntity( "<AddressValidateRequest USERID=\"xxxxxxxx\"><Address><Address1></Address1><Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State><Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>", HTTP.UTF_8);
se.setContentType("text/xml");
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://production.shippingapis.com/ShippingAPITest.dll?API=Verify&XML=");
httpPost.setEntity(se);
HttpEntity resEntity = httpPost.getEntity();
System.out.println(EntityUtils.toString(resEntity));
HttpResponse response = httpClient.execute(httpPost);
System.out.println(response.toString());
What can be the problem here?

Android post request

I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}

How do I pass a JSONObject to a PHP file?

I'm trying to submit some data formatted as a JSONObject to a web server. My understanding was that this is done with an httpclient on android and then a php file on the server. If that's not the case stop here and correct me, otherwise here's how i'm trying to send the data:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
String UN = username.getText().toString();
String PW = password.getText().toString();
String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\": \""+PW+"\"}}";
JSONDATA = new JSONObject(jString);
//JSONDATA = new JSONObject();
//JSONDATA.put("username", UN);
//JSONDATA.put("password", PW);
should i be using: httppost.setEntity(new UrlEncodedFormEntity(JSONDATA));
or should i be doing it like so:
StringEntity se = new StringEntity(JSONDATA.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpEntity entity;
entity = se;
httppost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httppost);
The question really is how are you planning to pull the data out on the server? What does your PHP look like? What may be easiest is to just pass the JSON as a parameter:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
String UN = username.getText().toString();
String PW = password.getText().toString();
String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\":\""+PW+"\"}}";
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("value", jString));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response;
response = httpclient.execute(httppost);
and then on the server side you can just do
<?php
$obj = json_decode($_POST['value']);
to retrieve it.

Categories

Resources