Apache HttpClient 4.1 - Proxy Settings - java

I am trying to POST some parameters to a server, but I need to set up the proxy. can you help me to to sort it "setting the proxy" part of my code ?
HttpHost proxy = new HttpHost("xx.x.x.xx");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("3128",proxy);
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("aranan", song));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
in = entity.getContent();
httpclient.getConnectionManager().shutdown();

Yes I sorted out my own problem,this line
httpclient.getParams().setParameter("3128",proxy);
should be
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
Complete Example of a Apache HttpClient 4.1, setting proxy can be found below
HttpHost proxy = new HttpHost("ip address",port number);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param name", param));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
InputStream in = entity.getContent();
httpclient.getConnectionManager().shutdown();

Non deprecated way of doing it (also in 4.5.5 version) is:
HttpHost proxy = new HttpHost("proxy.com", 80, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();

This is quick way I use to set the proxy:
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
...
HttpHost proxy = new HttpHost("www.proxy.com", 8080, "http");
HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();

When I use apache httpclient v4.5.5,I found HttpClient.getParams() is deprecated in v4.3,we should use org.apache.http.client.config.RequestConfig instead.
Code sample
shows that:
HttpHost target = new HttpHost("httpbin.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpGet("/");
request.setConfig(config);
CloseableHttpResponse response = httpclient.execute(target, request);

Related

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

MultipartEntity Files not uploading through device

Possibly this is a duplicate question but I have already tried all answer of this site but none of this working!
I am using MultipartEntity for image upload. It's working completely fine in Emulator but When I check in device its not working.
Below my code
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP);
HttpClient httpClient = new DefaultHttpClient(params);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://url.com/webservice_uploadvideo.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
FileBody filebodyVideopre = new FileBody(new File(videoUploadpathPre)); //pre
entity.addPart("fin_detail", filebodyVideopre);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
Here's my working code for multi-part image uploading. Yes it works in real device.
private int uploadImage(String selectedImagePath) {
try {
HttpClient client = new DefaultHttpClient();
File file = new File(selectedImagePath);
HttpPost post = new HttpPost(Constants.URL);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
Constants.BOUNDARY, Charset.defaultCharset());
entity.addPart(Constants.MULTIPART_FORM_DATA_NAME, new FileBody(file));
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "multipart/form-data; boundary=" + Constants.BOUNDARY);
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
int status = response.getStatusLine().getStatusCode();
return status;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Is my HTTPClient connection leaking sockets?

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

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?

Categories

Resources