I am receiving the below error message when I execute this code.
A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.:
I am unable to identify the resource leak in the below code. I'll be greatful if anyone point out what actually I am doing wrong.
HttpPost request = new HttpPost(url);
StringBuilder sb = new StringBuilder();
StringEntity entity = new StringEntity(jsonString);
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
HttpResponse response = null;
DefaultHttpClient httpclient = getHttpClientImpl();
BufferedReader reader = null;
InputStream in = null;
try {
response = httpclient.execute(request);
in = response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception se) {
Log.e("Exception", se + "");
throw se;
} finally {
if (in != null)
in.close();
if (reader != null)
reader.close();
if (client != null && client.getConnectionManager() != null) {
client.getConnectionManager().shutdown();
}
}
return sb.toString();
I don't really see any issues with that code, but I recommend closing all the idle connections in the pool.
public abstract void closeIdleConnections (long idletime, TimeUnit tunit)
Furthermore, there are some known issues with the DefaultHttpClient when not entirely configured correctly. I recommend using the AndroidHttpClient as an implementation of the HttpClient interface. Visit following documentation for the explanation:
http://developer.android.com/reference/android/net/http/AndroidHttpClient.html
Related
In my CountryActivity.java I have a HttpRequest to retrieve json information of the wikipedia.
This is the code I use AsyncTask:
private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
protected String doInBackground(URL... urls) {
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
is = httpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(line);
}
is.close();
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
showDialog(Integer.parseInt("Downloaded "));
}
}
And, to call the class in my activity I use new DownloadFilesTask();.
The problem is, when I debug my private class, the debugger stops in the line HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal"); and it can't even retrieve the json. Do you know what may be happening? My app doesn't crash or nothing...
This is my logcat: https://pastebin.com/EgVrjfVx
Open connection to url with HttpURLConnection and set setRequestMethod() to GET
URL obj = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
HttpURLConnection http = (HttpURLConnection) obj.openConnection();
http.setRequestMethod("GET");
then gets its input stream and read via BufferedReader to your build.
BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
String json_string = sb.toString(); // your json data
Check here full example to understand batter.
I've been stuck on this particular dilemma for some time, I have scoured the site and found some help, but not to my particular issue. I'm trying to connect to a website to extract JSON data from it. The host is what i'm not sure about:
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("www.wunderground.com", 80);
HttpGet httpGet = new HttpGet(urllink); // urllink is "api.wunderground.com/api/my_key/conditions/forecast/hourly/alerts/q/32256.json"
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(targetHost, httpGet);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (Exception e) {
// print stacktrace
return null;
} finally {
try {
instream.close();
} catch (Exception e) {
// print stacktrace
return null;
}
}
return stringBuilder.toString();
The host could either be www.wunderground.com or api.wunderground.com, but when I try either of them i get Unknown host exception.
I found the error. It was that I did not have the permission in the android manifest!
The call should be similar to:
http://api.wunderground.com/api/Your_Key/conditions/q/CA/San_Francisco.json
or as stated in the API,
GET http://api.wunderground.com/api/Your_Key/features/settings/q/query.format
In firts time if work with this source code in my app ,there is no problem ,but if I switch off wifi and try to get some resource from web service my app throws exception with state : Leak Found ,i use the close method of httpclient ,but nothing changes,after day ot two work with this code throws exception.
Stack print:
10-17 16:42:00.524: ERROR/AndroidHttpClient(931): Leak found
10-17 16:42:00.524: ERROR/AndroidHttpClient(931): java.lang.IllegalStateException: AndroidHttpClient created and never closed
Code :
public String getRequest(String url, ArrayList<NameValuePair> nameValuePairs){
String resp = "";
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
AndroidHttpClient httpclient = null;
try {
httpclient = AndroidHttpClient.newInstance("V");
httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
Reader reader = new InputStreamReader(instream, HTTP.UTF_8);
StringBuilder buffer = new StringBuilder("");
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
reader.close();
resp = buffer.toString().replace(""", "\"");
Log.d("V", "RESPONSE:-----\n" + resp + "\n--------------");
} catch (IOException e){
Log.e("V IOException [Send Request]","IO Exception");
if((e != null) && (e.getMessage() != null)){
Log.e("V",e.getMessage().toString());
}
} catch (Exception e) {
Log.e("V Exception [Send Request]","Exception Requester");
if((e != null) && (e.getMessage() != null)){
Log.e("V",e.getMessage().toString());
}
}finally {
if (httpclient != null && httpclient.getConnectionManager() != null) {
httpclient.close();
httpclient = null;
}
}
return resp;
}
Try: httppost.abort(); at the end. Also, I dont think create a httpclient for each request is a good idea, I think is better create the http client as instance variable and reuse for each request.
I might recommend using EntityUtils class to do what you are doing rather than what you are trying to do though. It will take care most of the problems
I am trying to read the buffer (android application) and set the value to my TextView 'httpStuff'. But i dont think i am getting some response from the URI.
I don't get any runtime errors. I tried many flavour of the same logic. Nothing seems to be working.
INTERNET permission is already set in the manifest. SdkVersion="15". Any help ?
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
httpStuf.setText( in.readLine());
I think you are missing the while loop and also, when you say only in.readLine(), may be it is returning you an empty line from the response, though it is having enough data.So make sure to read the reader entirely like this and check its contents.
while ((line = rd.readLine()) != null) {
httpStuf.setText(line+"\r\n");
}
Hope this will help you.
This code worked for me
InputStream is = response.getEntity().getContent();
String strResponse = inputStreamToString(is);
private String inputStreamToString(InputStream is)
{
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
// Read response until the end
try
{
while ((line = rd.readLine()) != null)
{
total.append(line);
}
} catch (IOException e)
{
Log.e(TAG, "error build string" + e.getMessage());
}
// Return full string
return total.toString();
}
try to get the status code of response and Then you can compare with the (HTTP status)
int responseCode=response.getStatusLine().getStatusCode()
I am using this method to simply catch the HTTP response and it works fine for me.
public String httpGetResponse(String url) {
try {
Log.i("HTTP Request", "httpGet Request for : " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//get.setHeader("Connection", "keep-alive");
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line + "\n");
}
return str.toString();
} catch (Exception e) {
Log.e("HTTP error", "Error in function httpGetResponse : "
+ e.getMessage());
return null;
}
}
I try to get HTML content, everything works find except 1 thing. It doesn't download whole code and skip the content which I want to extract(urls to images, names) and I have just blank classes 'obrazek'.
Here is the code i use to get source code:
String SourceCode(String adres) throws IllegalStateException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(adres);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()
)
);
String result = "";
while(reader.readLine() != null)
{
result += reader.readLine();
}
reader.close();
return result;
Thank you for help:)
You skip one line each time. should be
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
return result.toString();
BTW - I used StringBuilder to avoid creation of new String object each iteration - very recommended.