how to get cookies from volley response - android

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);
}
};

Related

Url working in Retrofit but not working in Volley

I have Url for Login. Its working and give response in Postman and Retrofit but not working with volley.
In volley its give error: com.android.volley.RedirectError
Why i geeting RedirectError. url working and give response in retrofit as well in postman.
Here is my Code:
public void Login(){
final String REGISTER_URL = "Here_My_Url";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("onResponse", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("eee123",error.toString());
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_email", st_email);
params.put("password", st_pass);
Log.e("params", " " + params);
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}

How to pass params and add authorization header in GET Request in Volley

I am trying to retrieve a response from my server in my Android App but getting "com.android.volley.ServerError"
E/Volley: [224669] BasicNetwork.performRequest: Unexpected response code 400 for http://52.74.115.250:8080/api/products
When I try in Postman,I do get a response.
This is my code for GET request:
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, Constants.productListUrlStr, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("jsonsucces","success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("jsonerror",error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Constants.getToken(getActivity()));
//headers=globalProvider.addHeaderToken(getActivity());
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
if (contract!=null){
if(contract._supplier!=null){
Log.d("checksupplier",contract._supplier);
params.put("_supplier",contract._supplier);
}
}
if(!globalProvider.ShangpingHeaderLoadCategory .equals("")){
params.put("category",globalProvider.ShangpingHeaderLoadCategory);
Log.d("checkcategoryhe",globalProvider.ShangpingHeaderLoadCategory);
}
return params;
}
};
globalProvider.addRequest(jsonObjectRequest);
what am I doing wrong?
There are few posts about getParams() not working anymore for JsonObjectRequest volley request.
Alternatively either you can use StringRequest or do a little tweak in your request as below
JSONObject jOb = new JSONObject();
try {
jOb.put("_supplier", contract._supplier);
jOb.put("category", globalProvider.ShangpingHeaderLoadCategory);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Constants.productListUrlStr, jOb, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("jsonsucces","success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("jsonerror",error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Constants.getToken(getActivity()));
//headers=globalProvider.addHeaderToken(getActivity());
return headers;
}
};
I figured out,Since I am passing query parameter I was constructing my url incorrectly.
String uri= String.format(Constants.productListUrlStr+"?_supplier=%1$s",contract._supplier);
StringRequest stringRequest=new StringRequest(Request.Method.GET, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("checksuc",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("checkstrerr",error.networkResponse.headers.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Constants.getToken(getActivity()));
//headers=globalProvider.addHeaderToken(getActivity());
return headers;
}
}
;
globalProvider.addRequest(stringRequest);

Add custom headers in volley request

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);
}
}

Android volley library is not accepting parameters in url from getParam()

Android volley library is not accepting parameters from getParam() method.If it is given in query String then it works.I tried both GET and POST it doesn't works. But I want to give parameters POST Method.please check the code I have posted below.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = AppConstants.WEBSERVICE_URL
+ AppConstants.WEBSERVICE_URL_POST_COMMENT;
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response_postComment", response);
Intent intent = new Intent(getApplicationContext(),
ReviewActivity.class);
intent.putExtra("serviceId", servicePosition);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<String, String>();
params.put("rating", ratingBar.getRating() + "");
params.put("com_content", comments.getText() + "");
params.put("user_id", AppConstants.APP_LOGIN_USER_ID);
params.put("comm_post_ID", AppConstants.arrListServiceDetail
.get(servicePosition).getId() + "");
return params;
}
};
getRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(getRequest);
getParam() method not working with GET request on volley.its working fine with POST methods.you have to set up complete URL with parameters.
I faced the same issue as you are facing now, but comes up with solution of making a custom request by making the core class Request as the super class of this request. In this i am passing params in constructor, then returning it to the getParams() overridden method as below:
public class RequestJson extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public RequestJson(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public RequestJson(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
AppController.getInstance().checkSessionCookie(response.headers);
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
AppController.getInstance().addSessionCookie(headers);
return headers;
}
}
Hope this will solve your problem.

Add custom headers with Volley library

I start using Volley for my application and I want to add custom headers for each request as a security identifier.
I'm using a JsonObjectRequest and overriding the getHeaders().
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
String mApiKey = "123";
headers.put("APIKEY", mApiKey);
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("param1", "1");
params.put("param2", "2");
params.put("param3", "3");
return params;
}
};
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
But I get this error:
E/Volley﹕ [23620] BasicNetwork.performRequest: Unexpected response code 401 for http://...
The AuthFailureError is thrown.
I also try to use StringRequest but same error.
If someone is in the same case and have solution, thank you in advance!
This is a basic concept how to override a header in a standard VolleyRequest
VolleyRequest networkRequest = new VolleyRequest(request.getHttpMethod(), mUrlBase + request.getUrlSuffix(), responseListener, errorListener) {
public String getBodyContentType() {
return "application/json; charset=" + getParamsEncoding();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
map.put("X-Device-Info","Android FOO BAR");
map.put("Accept-Language", acceptLanguage);
map.put("Content-Type", "application/json; charset=UTF-8");
return map;
}
public byte[] getBody() throws AuthFailureError {
try {
String json = request.toJson().toString();
if (json.length() < 3)
return ("{}").getBytes();
// log(json);
return json.getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "getBody(): request has no json");
e.printStackTrace();
}
return new byte[0];
}
};
public class CustomJsonObjectRequest extends JsonObjectRequest
{
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest,Response.Listener listener, Response.ErrorListener errorListener)
{
super(method, url, jsonRequest, listener, errorListener);
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put(Constants.accesstoken, Globals.getInstance().getAccessToken());
Logger.debugE(Constants.accesstoken, headers.toString());
return headers;
}
}

Categories

Resources