添加授权标头会导致android抛出filenotfoundexception

时间:2012-12-22 16:05:09

标签: android

当我添加一个授权头时,android会抛出一个filenotfound异常。如果我删除

con.setRequestProperty ("Authorization", basicAuth);

一切都好吗?

con = (HttpsURLConnection)url.openConnection();
            String userpass = userNameEditText.getText() + ":" +  passwordEditText.getText();

            String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

            con.setRequestProperty ("Authorization", basicAuth);

2 个答案:

答案 0 :(得分:1)

我没有验证它的工作原理,但请尝试执行以下操作

http://developer.android.com/reference/java/net/HttpURLConnection.html使用以下代码

Authenticator.setDefault(new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication(username, password.toCharArray());

   });
 }

执行此操作后,无需添加Authorization标头,因为此类将自动为您添加。

我的应用程序仅在某些设备上出现异常,并且将代码更改为此代码会在所有设备上为我修复。

我希望它会有所帮助

答案 1 :(得分:0)

我使用了以下内容,它就像一个魅力。

//Base64 basic http authentication
String textToBeEncoded = mName+":"+mPassword;
byte[] data = null;
data = textToBeEncoded.getBytes("UTF-8");
encoding = Base64.encodeToString(data,Base64.NO_WRAP);
Log.d(TAG,"encoded string: "+encoding);
//--------------------------------
HttpGet httpRequest = new HttpGet("//REQUEST URL//");
httpRequest.addHeader("Authorization", "Basic "+encoding);
HttpClient httpclient = new DefaultHttpClient();
response = httpclient.execute(httpRequest);

尝试使用这种方式..

希望它有效。

相关问题