2016-06-24 84 views
0

我想在使用Volley庫的Android應用程序中發出GET請求。此GET請求是使用基本HTTP身份驗證驗證帳戶憑據。我使用憑證在我的瀏覽器中驗證了URL,因爲它返回成功的XML。格式爲:排除帶有基本HTTP身份驗證的AuthFailureError(401)

http://username:[email protected]/api/account/verify_credentials.xml

其中usernamepassword顯然代表了真正的用戶憑據。凌空引發此錯誤:

BasicNetwork.performRequest: Unexpected response code 401 for http://username:[email protected]/api/account/verify_credentials.xml 

這是我的Android代碼處理該請求:

private static final String HTTP_PRE = "http://"; 
private static final String VERIFY_CREDENTIALS = "myanimelist.net/api/account/verify_credentials.xml"; 

public void verifyCredentials(String username, String password) { 
    RequestQueue queue = Volley.newRequestQueue(context); 
    String url = HTTP_PRE + username + ":" + password + "@" + VERIFY_CREDENTIALS; 

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 

     @Override 
     public void onResponse(String response) { 
      processResponse(response); 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      // handle error 
      Log.d(TAG, "error: " + error.getMessage()); 
     } 
    }); 

    queue.add(stringRequest); 
} 

將該溶液覆蓋()方法提供的相同的結果getHeaders: How does one use Basic Authentication with Volley on Android?

這裏是我的實現,解決方案:

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    Map<String, String> params = super.getHeaders(); 
    if (params == null){ 
     params = new HashMap<>(); 
    } 
    String creds = String.format("%s:%s", username, password); 

    params.put("Authorization", creds); 

    return params; 
} 

沒有哪個直接構建在URL的憑據返回此錯誤:

BasicNetwork.performRequest: Unexpected response code 401 for http://myanimelist.net/api/account/verify_credentials.xml 

如果有人能提供建議,我會很感激它。這是我第一次使用基本的HTTP身份驗證,所以我可能會漏掉一些明顯的東西。

回答

0

基本認證使用BASE64編碼。你錯過

String creds = String.format("%s:%s", username, password); 
creds = Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP); 

授權 HTTP標頭要求指明所使用的方法(基本|摘要)。最後你的標題應該看起來像這樣:

GET http://username:[email protected]/api/account/verify_credentials.xml 
Accept: text/xml,text/plain 
... 
Authorization: Basic XXXXXXXXXXXXXX==