我正在制作一个与Facebook API集成并使用REST API的Android应用程序,所以我使用的是Volley。但是,我尝试发出JSON数组的GET请求,并且必须包含Facebook授权令牌才能访问服务器。我在这方面看到的大多数问题都比较陈旧,看起来Volley现在提供了传递请求参数的支持(来自volley github页面):
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
但是当我制作并发出JsonArrayRequest时,我得到了一个com.android.volley.AuthFailureError。这是我的代码,有谁知道我做错了什么?
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Yo im here");
JSONObject requestParams = new JSONObject();
JSONArray paramArray = new JSONArray();
try {
requestParams.put("Authorization", "JWT (Facebook auth token)");
paramArray.put(requestParams);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(paramArray.toString());
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,
GET_MAP_MICS,
paramArray,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray micArray) {
try {
for (int i = 0; i < micArray.length(); i++) {
JSONObject jsonobject = micArray.getJSONObject(i);
int micId = jsonobject.getInt("micId");
String status = jsonobject.getString("status");
System.out.println("Good so far!");
double venLat = jsonobject.getDouble("venueLat");
double venLong = jsonobject.getDouble("venueLat");
System.out.println("got here, check it: " + venLat);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError e) {
System.out.println(e);
}
});
答案 0 :(得分:1)
GET
方法不仅仅需要POST
在您的情况下,您传递标题作为GET
方法的正文,您有传递标题
JsonObjectRequest request = new JsonObjectRequest(url, (JSONObject) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
/*Add your headers here*/
return super.getHeaders();
}
};
最终可能有两个相同的类名将在你的项目中,例如你使用的任何lib也使用volley lib这对我来说只发生一次