OkHttpClient connection leak warning from HttpURLConnection - android

I'm using HttpURLConnection to retrieve some configuration from a server. It works fine but for some reason I'm getting the following warning in the logcat:
OkHttpClient: A connection to ... was leaked. Did you forget to close a response body?
As pointed out in this question, Android is using OkHttp internally in HttpUrlConnection. What am I doing to cause this warning?
Here is the code I'm using:
HttpURLConnection connection = null;
OutputStream outputStream = null;
String result;
try {
URL url = new URL(CONFIG_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(READ_TIMEOUT_MILLI);
connection.setConnectTimeout(CONNECT_TIMEOUT_MILLI);
connection.setRequestMethod(REQUEST_METHOD);
connection.setDoInput(true);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Accept", "application/json");
outputStream = connection.getOutputStream();
try (DataOutputStream wr = new DataOutputStream(outputStream)) {
wr.write(data.toString().getBytes(STRING_ENCODING));
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
if (responseCode != HttpsURLConnection.HTTP_OK) {
Log.e(TAG, "HTTP error code: " + responseCode);
return;
}
try (InputStream stream = connection.getInputStream()) {
if (stream != null) {
result = readStream(stream, READ_STREAM_MAX_LENGTH_CHARS);
//...
connection.disconnect();
}
} catch (Throwable e) {
Log.e(TAG, "run: failed to parse server response: " +e.getMessage());
}
}
} catch (Exception e) {
Log.e(TAG, "HttpSendTask: failed to send configuration request " + data +": " +e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}

Closing the inputstream of the connection solved my problem.
Try to close it in the finally block :
connection.getInputStream().close()

Related

Connect Local Web servcies from android phone

I am trying to connect to web services running on my machine(localhost). I have tested from restClient and its working fine. But, I am unable to test them from android application(which I am working on). There seems to be a connection problem.
This is the calling code:
#Override
protected Void doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String mobileNo = params[0];
String format = "json";
try {
// Construct the URL for Login
JSONObject requestObject = new JSONObject();
requestObject.put(MOBILE_NO, mobileNo);
final String LOGIN_BASE_URL =
"http://192.168.42.251:8080/SpringSample/login";
Uri builtUri = Uri.parse(LOGIN_BASE_URL).buildUpon()
.build();
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// Request Body
OutputStream outStream = urlConnection.getOutputStream();
if (outStream == null) {
throw new ConnectException();
}
outStream.write(requestObject.toString().getBytes());
int responseCode = urlConnection.getResponseCode();
if (responseCode == 409) {
} else if (responseCode == 201) {
} else {
throw new ConnectException();
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
} catch (JSONException e) {
Log.e(LOG_TAG, "Error ", e);
} catch (ConnectException e) {
Log.e(LOG_TAG, "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
Exception is :
Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)

android HttpURLConnection wont desconnect?

aim using HttpURLConnection inside AsyncTask when i cancel AsyncTask and request abort or cancel the connection the AsyncTask stoped ok but HttpURLConnection still sending request and return with the values from the server
how i can make HttpURLConnection full stop cancel all requests or abort the request ?
this is the code i use
public static String post_string(String url, String urlParameters) throws IOException
{
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
} catch (MalformedURLException e) {
Log.e(Logger, "MalformedURLException While Creating URL Connection - " + e.getMessage());
throw e;
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL Connection - " + e.getMessage());
throw e;
}
conn.setDoOutput(true);
conn.addRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//if has Post inputs
conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.length()));
OutputStream os = null;
System.setProperty("http.keepAlive", "false");
try {
os = conn.getOutputStream();
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL OutputStream - " + e.getMessage());
throw e;
}
try {
os.write(urlParameters.toString().getBytes());
} catch (IOException e) {
Log.e(Logger, "IOException While writting URL OutputStream - " + e.getMessage());
throw e;
}
InputStream in = null;
try {
in = conn.getInputStream();
} catch (IOException e) {
Log.e(Logger, "IOException While Creating URL InputStream - " + e.getMessage());
throw e;
}
String output = null;
try {
output = slurp(in);
} catch (IOException e) {
Log.e(Logger, "IOException While Reading URL OutputStream - " + e.getMessage());
throw e;
} finally {
try {
os.close();
in.close();
} catch (IOException e) {
Log.e(Logger, "IOException While Closing URL Output and Input Stream - " + e.getMessage());
}
}
conn.disconnect();
Log.i("Server output " , output);
return output;
}
private static String slurp(InputStream in) throws IOException
{
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
and this is what i use to abort connection
conn.disconnect();
any advice how to abort ?
When you stop your AsyncTask like mTask.cancel(true); just call conn.disconnect();

How do i upload a file using HTTPUrlConnection urlConnection.setRequestMethod("PUT"); or HttpPut?

So, I can't get rid of this problem:
I need to upload a XML file and a .jpg file from my android app(API 8) to a HTTP server (win 2008 server with IIS 7.5). I've already enabled PUT verbs and uninstalled WebDav & webdav methods as suggested from previous searches.
Plus, i'm not sure i'm doing it right server side because i can't get any response back.
here's my code
URL fileurl = new URL("Server Upload Path");
HttpURLConnection urlConnection = (HttpURLConnection) fileurl
.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.setDoOutput(true);
urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
File upFile = new File("My Local File");
//I'm sure the file exists
FileInputStream fis = new FileInputStream(upFile);
BufferedInputStream bfis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int bufferLength = 0;
// now, read through the input buffer and write the contents to the
// file
while ((bufferLength = bfis.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
Sorry if I forget some info you may need to help. I'm new to android and IIS too.
Why not try a standard multi-part file upload request (based on POST and not PUT):
final static String MULTIPART_BOUNDARY = "------------------563i2ndDfv2rTHiSsdfsdbouNdArYfORhxcvxcvefj3q2f";
public static void sendFileToServer(String url, File logFiles) {
HttpURLConnection connection = null;
OutputStream os = null;
DataInputStream is = null;
try {
StringBuilder fullUrl = new StringBuilder(url);
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MULTIPART_BOUNDARY);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
os = new BufferedOutputStream(connection.getOutputStream());
if(os != null) {
os.write(("--" + MULTIPART_BOUNDARY + EOL).getBytes());
os.write(String.format("Content-Disposition:form-data;name=\"UploadedFile\";filename=\"%s\"\r\nContent-Type: application/x-zip-compressed\r\n\r\n", UPLOADED_FILE_NAME).getBytes());
// Upload file(s) data here and send
os.write((EOL + "--" + MULTIPART_BOUNDARY + "--" + EOL + EOL).getBytes());
os.flush();
os.close();
os = null;
}
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Process server response
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e1) {
} finally {
try {
if(os != null) {
os.close();
}
} catch (IOException e) {
Log.e(TAG, "sendFileToServer exception: close OutputStream", e);
}
try {
if(is != null) {
is.close();
}
} catch (IOException e) {
Log.e(TAG, "sendFileToServer exception: close InputStream", e);
}
if(connection != null) {
connection.disconnect();
}
}
}

Printing an InputStream in Logcat

I want to print the InputStream in logcat(for testing/later I will use it), my current code is as follows.
#Override
protected Void doInBackground(Void... params) {
try {
InputStream in = null;
int response = -1;
URL url = new URL(
"http://any-website.com/search/users/sports+persons");
URLConnection conn = null;
HttpURLConnection httpConn = null;
conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
if (in != null) {
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
// TODO: print 'in' from here
}
in.close();
in = null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
But I am not able to do this, so please check the code and add/modify the code to do this.
String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
And in your code:
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
Log.e(TAG, convertStreamToString(in));
Your TAG should be a constant like:
public final String TAG = YourActivity.class.getSimpleName();
Then you would do something like:
Log.e(TAG, "You're message here:", e)
e is your error from print stack.
You also want to make sure you import the Log in the Android library.
Also, after looking at your code, you might want to surround your httpConnection() with try/catch statement, that way you can catch the error, and put it in your Log file. You have the Log printing if your stream has something, or isn't null, but you want to know if you don't have a connection, and that would give you a null value.
Hope that helps.
Just add this code to if(in != null):
byte[] reqBuffer = new byte[1024];
int reqLen = 1024;
int read = -1;
StringBuilder result = new StringBuilder();
try {
while ((read = is.read(reqBuffer, 0, reqLen)) >= 0)
result.append(new String(reqBuffer, 0, read));
} catch (IOException e) {
e.printStackTrace();
}
Log.d("TAG", result.toString());

Android remote image ERROR

I want to Download An image from a remote server. But each time I get A nullpointer exception.
Method For Conencting to Server
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.i("Download ", "Response: OK");
}
else
Log.i("Download ", "Response: NOK");
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
Method For Creating Bitmap
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
Log.i("Download ", "InputStream Available: " +in.available());
bitmap = BitmapFactory.decodeStream(in);
Log.i("Download ", "Bitmap: " +bitmap.describeContents());
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
The null pointerException is thrown when I decodeStream, but when I use a different URL it works.
I run Apache on port 90. could this also have an effect if any.
try this I hope is working.
to connect with ftp use this code
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
to download file use this code
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}

Categories

Resources