我的代码如下:
public void getProfile(){
String LOGIN_REQUEST_TAG = "LOGIN_REQUEST_TAG";
String url = Constants.API_URL + "/users/profile";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("response")){
try {
Log.d("Data Response", responseOject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
/**
* Passing some request headers
*/
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer DGZjaza3saxL98g9ATRUQsolCxEZPBUd");
return headers;
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest,LOGIN_REQUEST_TAG);
该代码最初有效,但是在我们添加了api请求所需的标头之后,上面的代码似乎不起作用。
我是否在上面错误地编写了标题代码?感谢您的帮助。
logcat出现以下错误:
BasicNetwork.performRequest: Unexpected response code 401
答案 0 :(得分:1)
我认为您不应将getHeader()放在JsonObjectRequest的构造函数中。它应该放在匿名类块中
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("response")){
try {
Log.d("Data Response", responseOject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer DGZjaza3saxL98g9ATRUQsolCxEZPBUd");
return headers;
}
};
如果您想了解更多信息,请在volley中JsonObjectRequest的继承层次为Request-> JsonRequest-> JsonObjectRequest。您要覆盖的getHeaders()
方法是从Request基类派生的。