我尝试使用基本身份验证连接到我的服务器,但是当我设置授权标头时,它会导致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; }' –