Joh*_*ohn 5 android http-headers android-volley
我在 android 中调用 web 服务。因为我想调用 URL 我没有向服务器发送任何参数,只是调用 URL,
但它得到错误如 [10520] BasicNetwork.performRequest: Unexpected response code 401
我的代码是
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, Server.URL, null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
// display response
hideProgressDialog();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
此错误意味着您需要进行身份验证。您可以这样做将 getHeaders() 添加到您的代码中,因此它是这样的:
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, Server.URL, null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
// display response
hideProgressDialog();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
String creds = String.format("%s:%s","username","password");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
return params;
}
);
queue.add(getRequest);
Run Code Online (Sandbox Code Playgroud)
HTTP 401 表示网站需要身份验证,但未提供或失败。您需要验证自己的身份。未知您是否需要提供 HTTP 基本身份验证,或者 Web 服务是否需要特殊身份验证,并且只是巧妙地处理其返回值。
| 归档时间: |
|
| 查看次数: |
20594 次 |
| 最近记录: |