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?
Related
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.
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);
I have an app deployed on google app engine that uses the Apache HTTPClient. Recently as the app is getting more traffic, I have started running into exceptions where the sockets quota has been exceeded. The exception is
com.google.apphosting.api.ApiProxy$OverQuotaException: The API call remote_socket.SetSocketOptions() required more quota than is available.
I reached out to the App Engine team and they wanted me to check if my app was leaking sockets.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.spark.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("param1", "val1"));
nvps.add(new BasicNameValuePair("param2", "val2"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
Document doc = null;
try {
HttpEntity entity = response.getEntity();
doc = Jsoup.parse(entity.getContent(), "UTF-8", "");
EntityUtils.consume(entity);
} finally {
response.close();
httpclient.close();
}
This is what my http connection code looks like. Am I doing something wrong which may be causing the sockets to leak? Can I do something better?
this work for me :
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
// HttpPost httppost = new HttpPost("http://rafsanjan.uni-azad.my.com/json/darkhasr.php?shdaneshjo="+value_id+"&moavenat="+value_seaction+"&darkhast="+zir_item+"&startdate=test&tozih="+ value_descration); //???
try {
URIBuilder builder = new URIBuilder();
builder.setScheme("http")
.setHost("app.my.ac.com")
.setPort(1180)
.setPath("/json2/darkhasr.php")
.addParameter("shdaneshjo", value_id)
.addParameter("moavenat", value_seaction)
.addParameter("darkhast", value_item)
.addParameter("startdatet", "0")
.addParameter("tozih", value_descration)
.build();
// .fragment("section-name");
String myUrl = builder.toString();
Log.d("url=>",myUrl);
HttpPost httppost = new HttpPost(myUrl);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(8);
//nameValuePairs.add(new BasicNameValuePair("name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Log.d("RESPONSE",EntityUtils.toString(resEntity));
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
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?
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 :)