Android 截取认证头
当前,当我尝试发出get请求时,我必须首先进行身份验证。因此,在web上,我似乎需要使用getHeaders()并使用hashmap来提交凭据。然而,我的标题有一点额外的信息,我需要发送出去 我的标题如下所示: 我不确定是什么问题。我觉得我发送了所有正确的信息Android 截取认证头,android,json,authentication,android-volley,Android,Json,Authentication,Android Volley,当前,当我尝试发出get请求时,我必须首先进行身份验证。因此,在web上,我似乎需要使用getHeaders()并使用hashmap来提交凭据。然而,我的标题有一点额外的信息,我需要发送出去 我的标题如下所示: 我不确定是什么问题。我觉得我发送了所有正确的信息 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlJsonObj, new Response.Listener<J
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlJsonObj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
// JSONObject jsonArray = response.getJSONObject("response_message");
String message = response.getString("response_message");
Toast.makeText(getActivity(),
message,
Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
) {
@Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap<>();
String credentials = "ezhu:Ccare@123";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
headers.put("user-tz", "-330");
return headers;
}
};
requestQue.add(jsonObjectRequest);
}
JsonObjectRequest-JsonObjectRequest=new-JsonObjectRequest(Request.Method.GET,urlJsonObj,new-Response.Listener()){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
//JSONObject jsonArray=response.getJSONObject(“response_message”);
String message=response.getString(“response_message”);
Toast.makeText(getActivity(),
消息
Toast.LENGTH_LONG).show();
}捕获(JSONException e1){
e1.printStackTrace();
}
}
}
,
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(“截击”、“错误”);
}
}
) {
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map headers=newhashmap();
String credentials=“ezhu:Ccare@123";
字符串auth=“基本”
+Base64.encodeToString(credentials.getBytes(),Base64.NO_WRAP);
headers.put(“内容类型”、“应用程序/json”);
headers.put(“授权”,auth);
页眉.put(“用户tz”,“-330”);
返回标题;
}
};
add(jsonObjectRequest);
}
我的日志中有一个401错误,它给了我URL。单击URL时,浏览器中会打开一个选项卡,显示以下内容:
{“error_message”:“Missing request method parameter”,“error_code”:“1”,“error”:“Missing request header'user tz'for method parameter of type String”}
您的代码似乎是正确的。您可以尝试在日志中查找一些内容。当我处理类似问题时,我发现 W/System:忽略标头sessionID,因为其值为null
在我的日志中,如果您只是尝试在浏览器中转到API URL,那么在浏览器中测试REST URL的方式可能不正确(您的浏览器不会发送任何唯一的头,例如“user tz:-330”)。因此,您可能没有正确地“调试”它。尽管如此,就设置请求头而言,您的Android代码看起来确实正确。在过去,我使用了
Map headers=new ArrayMap()
,尽管我认为这不会有什么不同。我建议您仔细检查API文档,了解您试图使用的服务。@Adlip有什么解决方案吗?