我嘗試使用基本身份驗證連接到我的服務器,但是當我設置授權標頭時,它會導致getInputStream引發fileNotFound異常。如何使用android的httpURLconnection設置授權標頭
下面是相關代碼:
URL url = new URL(myurl);
//set up the connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);//this is in milliseconds
conn.setConnectTimeout(15000);//this is in milliseconds
String authHeader = getAuthHeader(userID,pass);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("authorization", authHeader);
//starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream(); //throws the fileNotFound exception
這裏是拋出的異常:
java.io.FileNotFoundException: http://<myIPaddress>/login/
古怪的是,我發現,fileNotFound例外是只有拋出,如果我嘗試設置請求屬性爲「授權」或「授權」或該字的任何變體。它是不拋出,如果我將它設置爲「內涵式」或「authosodifjsodfjs」(一個隨機字符串),如下:
conn.setRequestProperty("content-type",authHeader)//no exception thrown
conn.setRequestProperty("authosodifjsodfjs",authHeader)//no exception thrown
如果我不設置這個頭,我能夠連接到這個代碼的服務器,並得到我期待的適當的訪問被拒絕的消息。 我也可以連接到服務器並正確登錄,如果我使用python的「請求」模塊,所以它不是服務器的問題。
所以我的問題是:
1),如果有的話,我做錯了設置請求屬性爲「授權」的時候?如何正確設置auth頭? 2)如果這是一個HttpURLConnection的錯誤,我該如何提交錯誤報告?
謝謝。
編輯:有人建議從切換:
conn.setRequestProperty("Authorization", authHeader);
到:
conn.addRequestProperty("Authorization", authHeader);
這並沒有解決問題。它仍然拋出相同的異常。
編輯: 仍不確定爲什麼「授權」和「授權」導致fileNotFounExceptions,但使用全部大寫似乎正常工作。這裏是閃亮的新工作代碼:
conn.setRequestProperty("AUTHORIZATION",authHeader);
因此它看起來像它需要全部大寫。 「HTTP_」將自動添加到此標題的前面,因此服務器將看到的標題是「HTTP_AUTHORIZATION」,這應該是。
是什麼'getAuthHeader(字符串,字符串)'返回? – kcoppock
'private String getAuthHeader(String ID,String pass){ String encoded = Base64.encodeToString((ID +「:」+ pass).getBytes(),Base64.NO_WRAP); String returnThis =「Basic」+ encoded; return returnThis; }' –