Reputation: 33
I would like to ask why this network connection will appear FileNotFoundException error, I find a lot of places have not found the answer Thank you first
public static void sendOldHttpRequest(final String address, final IHttpCallbackListenet httpCallbackListenet) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
Log.i("tzf", "run: "+address);
URL url = new URL(address);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
httpCallbackListenet.onFinish(response.toString());
reader.close();
inputStream.close();
} catch (Exception e) {
httpCallbackListenet.onError(e);
} finally {
if (urlConnection!=null){
urlConnection.disconnect();
}
}
}
}).start();
}
error log:
03-05 20:59:49.835 17180-17268/com.example.tangzhifeng.paperairplane W/System.err: java.io.FileNotFoundException: https://moment.douban.com/api/stream/date/2017-03-05
03-05 20:59:49.835 17180-17268/com.example.tangzhifeng.paperairplane W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
03-05 20:59:49.835 17180-17268/com.example.tangzhifeng.paperairplane W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
03-05 20:59:49.836 17180-17268/com.example.tangzhifeng.paperairplane W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
03-05 20:59:49.836 17180-17268/com.example.tangzhifeng.paperairplane W/System.err: at com.example.tangzhifeng.paperairplane.util.HttpUtil$2.run(HttpUtil.java:61)
03-05 20:59:49.836 17180-17268/com.example.tangzhifeng.paperairplane W/System.err: at java.lang.Thread.run(Thread.java:818)
Upvotes: 2
Views: 3341
Reputation: 328
An HttpURLConnection will throw a FileNotFoundException for HTTP status codes 400 and above. You can use getResponseCode() to check the response status code before reading the content. Maybe your request is bad? Or you don't have the access to requested resource.
You could do sth like this
InputStream inputStream;
int responseStatusCode = urlConnection.getResponseCode();
if( status != HttpURLConnection.HTTP_OK ) {
inputStream = urlConnection.getErrorStream();
//Get more information about the problem
} else {
inputStream = urlConnection.getInputStream();
}
Upvotes: 7