Android错误FileNotFoundException

时间:2017-03-05 13:15:49

标签: java android

我想问一下为什么这个网络连接会出现FileNotFoundException错误,我发现很多地方都没有找到答案 先谢谢你

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

错误日志:

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)

1 个答案:

答案 0 :(得分:2)

HttpURLConnection 将为HTTP状态代码400及更高版本抛出 FileNotFoundException 。您可以在读取内容之前使用getResponseCode()检查响应状态代码。也许你的要求不好?或者您无权访问所请求的资源。

你可以这样做

InputStream inputStream;
int responseStatusCode = urlConnection.getResponseCode();
if( status != HttpURLConnection.HTTP_OK ) { 
    inputStream = urlConnection.getErrorStream();
    //Get more informations about the problem
} else {
    inputStream = urlConnection.getInputStream();
}