Android remote image ERROR - android

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

Related

OkHttpClient connection leak warning from HttpURLConnection

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

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)

Alternative to httpConnection.getContentLength()?

I call the following function to get the total files size to download:
private Uri askForFileSizeFromURL(URL url, String fileName) {
try {
URLConnection conn = url.openConnection();
HttpURLConnection httpConnection = conn instanceof HttpURLConnection ? (HttpURLConnection ) conn : null;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
bytesToDownload += httpConnection.getContentLength();
return null;
}
}
catch(ConnectException e) {
Log.d("2ndGuide", "ConnectException." + e);
downloadAborted = true;
return null;
}
catch(IOException e)
{
Log.d("2ndGuide", "IO Exception." + e);
}
return null;
}
I'm calling this function 31 times and it takes more than 23 secondes. Without this call the loop takes 320ms. So the problem comes from this code.
Is there a quicker way to get files size from a remote server on Internet?
Regards,
Alain

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

HttpGet in android .. what am I doing wrong?

I have this code from a book I have to learn about Android .. what's wrong?
I always get 01 Error Connecting which is an exception in my code while establishing http connection.
public class HttpImgActivity extends Activity {
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null; // creating My input
int response = -1;
URL url= new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection)) // if not a valid URL
throw new IOException ("NOT an Http connection");
try{
HttpURLConnection httpconn = (HttpURLConnection) conn;
httpconn.setAllowUserInteraction(false); // prevent user interaction
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect(); //initiates the connection after setting the connection properties
response = httpconn.getResponseCode(); // getting the server response
if(response == HttpURLConnection.HTTP_OK ) // if the server response is OK then we start receiving input stream
{ in = httpconn.getInputStream(); }
} // end of try
catch(Exception ex)
{
throw new IOException(" 01 Error Connecting");
}
return in; // would be null if there is a connection error
} // end of my OpenHttpConnection user defined method
*/
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap= null;
InputStream in = null;
try
{
in = getInputStreamFromUrl(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1)
{
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
return bitmap; // this method returns the bitmap which is actually the image itself
}
ImageView img;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.egyphone.com/wp-content/uploads/2011/05/Samsung_Galaxy_S_II_2.jpg");
img =(ImageView) findViewById(R.id.myImg);
img.setImageBitmap(bitmap);
}
}
Any ideas?
It seems you catch your exception, but you don't use it for anything.
Try changing throw new IOException(" 01 Error Connecting"); to throw new IOException(ex.toString());
And you should think about using Android's logging tools, instead to see your errors through logcat:
...
catch(Exception ex)
{
Log.e("CONNECTION", ex.toString(), ex);
}
...
This makes debugging easier IMO.

Categories

Resources