Add custom headers in volley request - android

I have a Volley Request code
RequestQueue queue = Volley.newRequestQueue(this);
String url =<My URL>;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
How do I set a header called Authorization in this??

Override getHeaders in request like:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = super.getHeaders();
if(params==null)params = new HashMap<>();
params.put("Authorization","Your authorization");
//..add other headers
return params;
}
};

you can write a class extends Request.(override getHeaders() and so on)
just like
public abstract class AbsRequest<T> extends Request<T>{
public AbsRequest(int method, String url, Response.ErrorListener listener) {
this(method, url, null, listener);
}
public AbsRequest(int method, String url, Map<String, String> params, Response.ErrorListener listener) {
this(method, url, params, null, listener);
}
public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, Response.ErrorListener listener) {
this(method, url, params, head, null, listener);
}
public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
this(method, url, params, null, head, bodyContentType, listener);
}
public AbsRequest(int method, String url, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
this(method, url, null, body, head, bodyContentType, listener);
}
private AbsRequest(int method, String url, Map<String, String> params, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
super(method, url, listener);
}
}
for more information you can see https://github.com/Caij/CodeHub/blob/master/lib/src/main/java/com/caij/lib/volley/request/AbsRequest.java
how to use can see https://github.com/Caij/CodeHub/tree/master/app/src/main/java/com/caij/codehub/presenter/imp

A call to super.getHeaders() throws UnSupportedOperationException.
remove super.getHeaders() to get rid off that.

This here is a sample volley request showing how to add headers
private void call_api(final String url){
if(!this.isFinishing() && getApplicationContext() != null){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
resultsTextView.setVisibility(View.INVISIBLE);
loader.setVisibility(View.VISIBLE);
}
});
Log.e("APICALL", "\n token: " + url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("APICALL", "\n response: " + response);
if(!FinalActivity.this.isFinishing()){
try {
JSONObject response_json_object = new JSONObject(response);
JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
last_results_type = k.getString("type");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
loader.setVisibility(View.INVISIBLE);
resultsTextView.setText(result);
resultsTextView.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
finish();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("APICALL", "\n error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
finish();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("apiUser", "user");
headers.put("apiKey", "key");
headers.put("Accept", "application/json");
//headers.put("Contenttype", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("location", "10.12 12.32");
return map;
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}

Related

How to send parameters to backend, and get response message, using GET method in volley, android?

I want to send three parameters "guestEmail", "latitude" and "longitude" to backend and get a message of success from backend if it is successful.
I have tried doing this:
public void myGetFunc()
{
final String url = "....";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("guestEmail", "abc#xyz.com");
params.put("latitude", "12");
params.put("longitude", "12");
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
This method is invoked when the 'SOS' button is clicked.
But right now, nothing happens on clicking the 'SOS' button.
Please help!
If you are going to use GET you query parameters and build the string yourself
private static final String URL = "http://www.test.com?value1={val1}&value2={val2}";
String requestString = URL;
requestString.replace("{val1}", "1");
requestString.replace("{val2}", "Bob");
StringRequest strreq = new StringRequest(Request.Method.GET,
requestString,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
If you are going to use POST us a body
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
If you want to pass parameters than you need to use POST method otherwise for GET , just pass values in URL itself.

Sending POST Data in Android for Kairos API

I am looking to do as per the image says:
Following is the code I am trying to implement from that image:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://api.kairos.com/enroll";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.i("Response is: " , response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mTextView.setText("That didn't work!");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("app_id", "4985f625");
params.put("app_key", "aa9e5d2ec3b00306b2d9588c3a25d68e");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
Now I do not get how to add that JSONObject part into my POST Request, and also how to add the Content-Type Header.
I found a similar question here. See the code below. You have to override the getBodyContentType method.
public String getBodyContentType()
{
return "application/json";
}
for content type header you can do the following
StringRequest request = new StringRequest(Request.Method.PUT,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(#NonNull VolleyError error) {
if (error.networkResponse != null) {
errorListener.onErrorResponse(error.networkResponse.statusCode, null);
} else {
Log.e(TAG, "An error occurred while trying to verify sms: ", error);
errorListener.onErrorResponse(500, null);
}
}
}) {
#NonNull
#Override
protected Map<String, String> getParams() {
return data;
}
#NonNull
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type",
"application/x-www-form-urlencoded");
return headers;
}
};
And for send Json object I suggest create Json object like this
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
} catch (JSONException e) {
e.printStackTrace();
}
Then you can pass this object as string by jsonObject.toString() and pass it in parameters like pass any string like the following
#NonNull
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("json", jsonObject.toString();
return params;
}

how to get cookies from volley response

I need to get the cookies from server response. For network calling i am using volley library.
getRequest(String url, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
try {
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null, responseListener
, errorListener) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getAuthHeader(context);
}
};
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
req.setRetryPolicy(policy);
req.setShouldCache(false);
addToRequestQueue(req);
} catch (Exception e) {
e.printStackTrace();
}
public static Map<String, String> getAuthHeader(Context context) {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", auth);
headerMap.put("Api-key", API_KEY);
headerMap.put("Content-Type", CONTENT_TYPE);
return headerMap;
}
StringRequest req = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error",error.getMessage());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getAuthHeader(context);
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
Log.i("response",response.headers.toString());
Map<String, String> responseHeaders = response.headers;
String rawCookies = responseHeaders.get("Set-Cookie");
Log.i("cookies",rawCookies);
return super.parseNetworkResponse(response);
}
};

Android Volley Request with Body

Is it possible to send a simple text in the body of a StringRequest using DELETE-Method?
I couldn't find any example where somebody put something in the body of a request...
This is my request and I want to add "{'deviceid':'xyz'}" to the body (method is DELETE):
final StringRequest stringRequest = new StringRequest(method, url + "?token=" + token, new Response.Listener<String>() {
#Override
public void onResponse(String jsonResponse) {
// do something
}, new Response.ErrorListener() {
// do something
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("api-version", "1");
return headers;
}
};
This because Volley doesn't send the Body for DELETE by default. Only for POST, PUT and PATCH. Unfortunate to say the least
There is a workaround for it listed here: Volley - how to send DELETE request parameters?
Try this:
public class StringJSONBodyReqest extends StringRequest {
private static final String TAG = StringJSONBodyReqest.class.getName();
private final String mContent;
public StringJSONBodyReqest(int method, String url, String content, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
mContent = content;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("api-version", "1");
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
body = mContent.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
#Override
public String getBodyContentType() {
return "application/json";
}
}
mContent is your json String
StringRequest stringRequest = new StringRequest(StringRequest.Method.PUT,
BASE_URL + "/addItem",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle error
}
}) {
#Override
public byte[] getBody(){
String jsonString = json to send;
return jsonString.getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyRequestQueue.getInstance().addRequest(stringRequest);

How to send base64 image as a atachment in volley?

i should to send image in request body, how can I make it?
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String url = getString(R.string.url) + "auth/avatar?token="+ Utils.getToken(getActivity());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d("myLogs", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("avatar", encodedImage);
return params;
}
};
requestQueue.add(request);
I have read this article, but it doesn't help me.

Categories

Resources