2017-03-05 131 views
0

我想問一下爲什麼這個網絡連接會出現FileNotFoundException異常錯誤,我找了很多地方都沒有找到答案 謝謝先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) 
+0

最有可能的,Android是正從'的https的HTTP 404響應:// moment.douban.com/API /流/日期/ 2017-03-05' 。我不知道爲什麼。 – CommonsWare

+0

也許文件受到保護。或者試圖檢索文件的機器人會收到與用戶不同的結果。嘗試檢索一個HTML文件。打開一個流到google.com(或任何其他網站)並嘗試獲取索引文件 – Zoe

回答

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

是的,但我可以在瀏覽器中訪問,但無法訪問Android,好奇啊...... –

+0

您是否包含適當的權限清單文件? Bari

+0

權限添加,因爲在HTTP403之前 –

相關問題