我使用下面的代码和Volley lib来调用api。 在这个传递方法和网址中,我还需要传递标题。
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
"http//xyz", null, new Response.Listener<JSONObject>()
答案 0 :(得分:2)
像这样:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, new JSONObject(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//Handle response here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Handle errors here
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("HEADER KEY", "HEADER VALUE");
return params;
}
};
requestQueue.add(jsonObjectRequest);
答案 1 :(得分:1)
您必须覆盖getHeaders()
才能输入标题信息。按照这个 -
private void callToApi(){
String serverUrl = serverUrl+"&lat="+99.9999+"&lng="+76.9887;
JsonObjectRequest weatherUpdateRequest = new JsonObjectRequest
(Request.Method.GET, serverUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(CLASS_NAME, " JSON: " + response.toString());
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer ghbgrbhrgt");
return headers;
}
};
Volley.newRequestQueue(getApplicationContext()).add(weatherUpdateRequest);
}