slinden77 slinden77 - 5 months ago 29
Android Question

java.io.FileNotFoundException only occurs when run inside AsyncTask

I have an odd problem; if I run this code I get a java.io.FileNotFoundException: https://graph.facebook.com/debug_token?input_token=1234&access_token=1234. This only occurs when I call

client.getInputStream()
inside my
AsyncTask
. Click the link: it clearly works.

Let's call this case 1.

Now, when I run the exact same code outside of my
AsyncTask
, I get a NetworkOnMainThreadException, but
client.getInputStream()
works...

Consider this case 2.

I know why I get the
NetworkOnMainThreadException
in case 2, but I don't understand why the
FileNotFoundException
only happens in case 1, and not in case 2. The code is identical! I've been looking at this for hours and I just don't know what I am doing wrong.

EDIT: apperently the
FileNotFoundException
occurs because of an error response code. I figured this out by getting the error stream with
.getErrorStream()
when the exception occurs.

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import javax.net.ssl.HttpsURLConnection;

public class Temp {

private String getResponse(InputStream stream){
Scanner s = new Scanner(stream).useDelimiter("\\A");
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}

public void run(String url){
URL uri;
HttpsURLConnection client = null;
try {
uri = new URL(url);
client = (HttpsURLConnection) uri.openConnection();
client.setReadTimeout(15*1000);
} catch (IOException e) {
e.printStackTrace();
}
new RetrieveStream().execute(client);
}

private class RetrieveStream extends AsyncTask<HttpsURLConnection, Void, String> {
private String returnString = null; //don't change this!
HttpsURLConnection client;
@Override
protected String doInBackground(HttpsURLConnection... client) {
try {
this.client = client[0];
InputStream stream = this.client.getInputStream();
Log.d(getClass().getSimpleName(), "response: "+getResponse(this.client.getInputStream()));
} catch (FileNotFoundException e) {
Log.d(getClass().getSimpleName(), "error output: "+getResponse(this.client.getErrorStream()));
e.printStackTrace();
} catch (IOException e) {
Log.d(getClass().getSimpleName(), "error: "+getResponse(this.client.getErrorStream()));
e.printStackTrace();
}
this.client.disconnect();
return returnString;
}

protected void onPostExecute(String output) {
Log.d(getClass().getSimpleName(), "output: "+output);
}
}
}

Answer

It's not very clear why the FileNotFoundException occurs, but I was able to get the response with .getErrorStream() instead of .getInputStream(). My question is answered accordingly. Please ignore the other answers, they provide no solutions.

Comments