android DefaultHttpClient POST to service wcf .svc - java

I hava this code
public static String methodPost(final String url, final String dataToPost) throws ClientProtocolException,
IOException, IllegalStateException, Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(dataToPost);
se.setContentEncoding("UTF-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return streamToString(httpEntity.getContent());
}
I post this in IPHONE and work perfectly:
#"{\"var1\":\"Value1\"}{\"var2\":[{\"item1\":\"1\"},{\"item1\":\"Value2\"}]}"
when I post also in ANDROID.
Response return HTTP 1 400
example:
methodPost(url, "{\"var1\":\"Value1\"}{\"var2\":[{\"item1\":\"1\"},{\"item1\":\"Value2\"}]}");
but, I post this
methodPost(url, "{\"var1\":\"Value1\"}{\"var2\":\"Value2\"}");
this work perfectly only when I use "[ ]" i have some error
sorry for my english :)

Related

Apache Http Client Unit Test Issue | HttpResponseProxy{HTTP/1.1 406 Not Acceptable

While unit testing my code of posting payload to an endpoint I am getting exception like HttpResponseProxy{HTTP/1.1 406 Not Acceptable}
HttpClient httpClient = mock(HttpClient.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
doReturn(HttpURLConnection.HTTP_CREATED).when(statusLine).getStatusCode();
doReturn(httpResponse).when(httpClient).execute(any());
HttpResponse response = service.postData("payload to be sent");
Assertions.assertNotNull(response);
Assertions.assertNotNull(response.getStatusLine().getStatusCode());
Assertions.assertNotNull(response.getEntity());
Assertions.assertNotNull(response.getHeaders("Authorization"));
Assertions.assertNotNull(response.getHeaders("Content-type"));
Actual Code -
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httppost = new HttpPost(endpoint);
httppost.setHeader("Authorization", "Bearer " + token);
httppost.setEntity(payloadString);
httppost.setHeader("Content-type", "application/json");
httpresponse = httpclient.execute(httppost);
responseCode = httpresponse.getStatusLine().getStatusCode();
}
return responseCode;
Please guide where I am going wrong and the right way to do this.

HttpPost Posting Complex JSONObject in the Body of the Request

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

Post custom object from Android client to JAX-RS

I have a simple android client with following code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.0.11:8080/MyWeb/Test/tests/save");
httpPost.addHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(new Gson().toJson(new Hank()), HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
The goal is to trigger a response from the JAX-RS resource on the server. Here is the server code:
#Path("/save")
#POST
#Produces("application/json")
#Consumes("application/json")
public Hank saveHank(Hank hank) throws JSONException {
System.out.println(hank);
return hank;
}
The responseBody is a HTML-page with the information that the resource is not available. What is wrong?

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

Categories

Resources