Is my HTTPClient connection leaking sockets? - java

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

Related

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

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

Http cookie store in Android

I am developing an Android client for the site with authorization. I have a post method. Example my code:
public void run() {
handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
httpClient = new DefaultHttpClient();
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
HttpResponse response = null;
try{
switch (method){
case POST:
HttpPost httpPost = new HttpPost(url);
httpPost.setHeaders(headers);
if (data != null) httpPost.setEntity(new StringEntity(data));
response = httpClient.execute(httpPost);
break;
}
processEntity(response);
}catch(Exception e){
handler.sendMessage(Message.obtain(handler, HttpConnection.DID_ERROR, e));
}
ConnectionManager.getInstanse().didComplete(this);
}
How to keep cookies?
You get your cookies from HttpResponse response:
Header[] mCookies = response.getHeaders("cookie");
and add them to your next request:
HttpClient httpClient = new DefaultHttpClient();
//parse name/value from mCookies[0]. If you have more than one cookie, a for cycle is needed.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpGet = new HttpGet("http://www.domain.com/");
HttpResponse response = httpClient.execute(httpGet, localContext);

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

Apache HttpClient 4.1 - Proxy Settings

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

Categories

Resources