簡體   English   中英

HttpURLConnection#getResponseCode()導致FileNotFoundException

[英]HttpURLConnection#getResponseCode() results in FileNotFoundException

我目前正在嘗試訪問位於https://fnbr.co/api/shop下的Web API(不是我的)。

我正在運行的代碼基本上是這樣的:

URL url = new URL("https://fnbr.co/api/shop");

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();

System.out.println(conn.getResponseCode()); // second error

BufferedReader reader = new BufferedReader(
    new InputStreamReader(conn.getInputStream())); // first error

// read from this reader

控制台輸出(響應代碼)為

404

FileNotFoundException: https : //fnbr.co/api/shop

conn.getInputStream()和另一行

FileNotFoundException: https : //fnbr.co/api/shop

conn.getResponseCode()

我的問題出在哪里(因為404應該表示該文件不存在,但是我可以通過瀏覽器訪問它)?

HTTP 404表示請求的URL不存在。 這意味着在您的情況下,GET https://fnbr.co/api/shop地址后面沒有任何內容。 也許您需要使用其他協議,例如PUT,POST等:

404 Not Found找不到請求的資源,但將來可能可用。 客戶的后續請求是允許的。

是HTTP響應代碼的正式描述。

如果您返回HTTP 200,則需要處理客戶端代碼中的錯誤,例如HTTP 404,以便讀取響應(請記住,它不是文件,這是請求-響應!),如下所示:

if (conn.getResponseCode() == 200) {
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
}
conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();

對於GET請求,這看起來很虛假。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM