How can custom headers be set for a Volley request? At the moment, there is way to set body content for a POST request. I've a simple GET request, but I need to pass the custom headers alongwith. I don't see how JsonRequest class supports it. Is it possible at all?
The accepted answer with getParams() is for setting POST body data, but the question in the title asked how to set HTTP headers like User-Agent. As CommonsWare said, you override getHeaders(). Here's some sample code which sets the User-Agent to 'Nintendo Gameboy' and Accept-Language to 'fr':
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
It looks like you override public Map<String, String> getHeaders(), defined in Request, to return your desired HTTP headers.
If what you need is to post data instead of adding the info in the url.
public Request post(String url, String username, String password,
Listener listener, ErrorListener errorListener) {
JSONObject params = new JSONObject();
params.put("user", username);
params.put("pass", password);
Request req = new Request(
Method.POST,
url,
params.toString(),
listener,
errorListener
);
return req;
}
If what you want to do is edit the headers in the request this is what you want to do:
// could be any class that implements Map
Map<String, String> mHeaders = new ArrayMap<String, String>();
mHeaders.put("user", USER);
mHeaders.put("pass", PASSWORD);
Request req = new Request(url, postBody, listener, errorListener) {
public Map<String, String> getHeaders() {
return mHeaders;
}
}
You can see this solution. It shows how to get/set cookies, but cookies are just one of the headers in a request/response. You have to override one of the Volley's *Request classes and set the required headers in getHeaders()
Here is the linked source:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* #param method
* #param url
* #param params
* A {#link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* #param listener
* #param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
#Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* #see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
#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
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* #see com.android.volley.Request#getHeaders()
*/
#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>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
And MyApp class:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
#Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* #param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
In Kotlin,
You have to override getHeaders() method like :
val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, PAYLOAD_BODY_IF_YOU_WISH,
Response.Listener {
// Success Part
},
Response.ErrorListener {
// Failure Part
}
) {
// Providing Request Headers
override fun getHeaders(): Map<String, String> {
// Create HashMap of your Headers as the example provided below
val headers = HashMap<String, String>()
headers["Content-Type"] = "application/json"
headers["app_id"] = APP_ID
headers["app_key"] = API_KEY
return headers
}
}
Looking for solution to this problem as well.
see something here: http://developer.android.com/training/volley/request.html
is it a good idea to directly use ImageRequest instead of ImageLoader? Seems ImageLoader uses it internally anyway. Does it miss anything important other than ImageLoader's cache support?
ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...
// Retrieves an image specified by the URL, displays it in the UI.
mRequestQueue = Volley.newRequestQueue(context);;
ImageRequest request = new ImageRequest(url,
new Response.Listener() {
#Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new Map<String, String>();
params.put("User-Agent", "one");
params.put("header22", "two");
return params;
};
mRequestQueue.add(request);
try this
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
Map<String, String> headers = new HashMap<String, String>();
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
You can make a custom Request class that extends the StringRequest and override the getHeaders() method inside it like this:
public class CustomVolleyRequest extends StringRequest {
public CustomVolleyRequest(int method, String url,
Response.Listener<String> listener,
Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("key1","value1");
headers.put("key2","value2");
return headers;
}
}
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("AppId", "xyz");
return headers;
}
}
As addition I'd like to share something I found regarding the Content-Type:
On top of
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
.
.
.
return params;
}
I had to add:
#Override
public String getBodyContentType() {
return /*(for exmaple)*/ "application/json";
}
Don't ask me why, I just thought it might help some others that can't get the Content-Type set right.
Here is setting headers from github sample:
StringRequest myReq = new StringRequest(Method.POST,
"http://ave.bolyartech.com/params.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws
com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
try this
public void VolleyPostReqWithResponseListenerwithHeaders(String URL,final Map<String, String> params,final Map<String, String> headers,Response.Listener<String> responseListener) {
String url = URL;
Log.i("url:", ":" + url);
StringRequest mStringRequest = new StringRequest(Request.Method.POST,
url, responseListener, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
//Log.d("Error.Response", error.getLocalizedMessage());
}
}){
#Override
protected Map<String, String> getParams() {
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
};
mStringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mStringRequest.setShouldCache(true);
// dialog.show();
SingletonRequestQueue.getInstance(context).addToRequestQueue(mStringRequest);
}
That is my code, dont forget = object: if don't put don't works
val queue = Volley.newRequestQueue(this)
val url = "http://35.237.133.137:8080/lamarrullaWS/rest/lamarrullaAPI"
// Request a string response from the provided URL.
val jsonObjectRequest = object: JsonObjectRequest(Request.Method.GET, url, null,
Response.Listener { response ->
txtPrueba.text = "Response: %s".format(response.toString())
},
Response.ErrorListener { txtPrueba.text = "That didn't work!" }
)
{
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers.put("Content-Type", "application/json")
return headers
}
}
queue.add(jsonObjectRequest)
Related
I'm trying to use KairosAPI's enroll POST request using Android Volley. However I keep getting Error 1002, image one or more required parameters are missing. I've tried two ways to add the parameters into the body of the JSON, which I've outlined in the code.
This is my code-
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequestToEnrollPersonInGallery();
}
public void postRequestToEnrollPersonInGallery() {
final String appId = "3e12****";
final String appKey = "156e06fd782a3304f085f***********";
String mainUrl = "https://api.kairos.com/";
String enrollRequestUrl = "enroll";
requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, mainUrl + enrollRequestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("app_id", appId);
params.put("app_key", appKey);
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
/*params.put("image", "\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg\"");
params.put("subject_id", "\"subject_id\":\"12345\"");
params.put("gallery_name", "\"gallery_name\":\"FirstGallery\""); -- i tried this too*/
return params;
}
};
requestQueue.add(stringRequest);
}
}
You aren't posting JSON.
You can either
1) Learn to use JsonObjectRequest
final JSONObject body = new JSONObject();
body.put(... , ...);
Request request = new JsonObjectRequest(url, body, ...);
2) Actually post a JSON String.
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject params = new JSONObject();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
return params.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
My Volley code used to work properly like this:
StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//parameters are declared above this part of the code
return parameters;
}
};
Then I got Error 403 from a php file on server-side. People were suggesting adding headers to request. So I change my code to this:
StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//parameters are declared above this part of the code
return parameters;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/form-data; charset=utf-8");
return headers;
}
};
After adding headers I was able to get rid of Error 403 but now Volley is not passing my parameters to server. Everything seem to be null.
I also tried to use getBodyContentType() instead of GetHeaders() but still same problem occurs.
Edit, the whole code:
public static void execute(final Request request, Context context){
if(queue == null)
queue = Volley.newRequestQueue(context);
final Map<String, String> parameters = new HashMap<String, String>();
for(int index = 0; index < request.getParameters().length; index++){
parameters.put(request.getParameters()[index].getName(), request.getParameters()[index].getValue());
}
int method;
switch (request.getRequestType()){
case GET: method = Method.GET; break;
case POST: method = Method.POST; break;
default: method = Method.POST; break;
}
String URL = request.getURL();
VolleyRequest newPostRequest = new VolleyRequest
(com.android.volley.Request.Method.POST, URL, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
request.onResponse(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
// TODO Auto-generated method stub
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "aapplication/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};
queue.add(newPostRequest);
}
server-side:
<?php
require_once 'connection.php';
$name = $_POST['name'];
$token = $_POST['token'];
if(strlen($name) < 4){
$feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("SELECT name FROM user WHERE name = :name");
$sql->bindParam(':name', $name);
$sql->execute();
if($sql->rowCount() > 0){
$feed = array("Result" => "Failed", "Message" => "This name is already taken!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)");
$sql->bindParam(':name', $name);
$sql->bindParam(':token', $token);
$sql->execute();
$id = $conn->lastInsertId();
$feed = array("Result" => "Successful", "ID" => $id);
echo json_encode($feed);
?>
Follow this way. Use this custom request class.
public class VolleyRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public VolleyRequest(String url, Map<String, String> params,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public VolleyRequest(int method, String url, Map<String, String> params,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
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));
}
}
}
And implement like this way -
Map<String, String> params = new HashMap<String, String>();
params.put("param_1", "value_1");
params.put("param_2", "value_2");
VolleyRequest newPostRequest = new VolleyRequest
(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(CLASS_NAME, " Response: " + 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("Content-Type", "application/form-data; charset=utf-8");
return headers;
}
};
Volley.newRequestQueue(context.getApplicationContext()).add(newPostRequest);
Edit2: ServerSide code:
require_once 'connection.php';
$name = $_POST['name'];
$token = $_POST['token'];
if(strlen($name) < 4){
$feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("SELECT name FROM user WHERE name = :name");
$sql->bindParam(':name', $name);
$sql->execute();
if($sql->rowCount() > 0){
$feed = array("Result" => "Failed", "Message" => "This name is already taken!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)");
$sql->bindParam(':name', $name);
$sql->bindParam(':token', $token);
$sql->execute();
$id = $conn->lastInsertId();
$feed = array("Result" => "Successful", "ID" => $id);
echo json_encode($feed);
Actually I had a similar problem as yours with my Volley StringRequest.
I needed to pass Authorization header as well as parameters to the server(CodeIgniter in my case)
I changed the Content type line from json to application/x-www-form-urlencoded; charset=UTF-8 and voila!!! It worked
i.e
//Setting Headers
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Authorization-token", func.getAuthorizationToken(getActivity()));
return headers;
}
//Adding parameters
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "" + func.getSharedUserID(getActivity()));//Logged in user
Log.e("Passed User ID: ", func.getSharedUserID(getActivity()));
return params;
}
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.
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;
}
}
I am trying create a custom BasicAuthentication with Volley. I have a class ApplicationController that I implemented methods getHeaders and works fine with all application, but now, I have a method that I need send other BasicAuthentication with other Parameters. To do it I am trying #Override the getHeaders() of class ApplicationController. It doesnt works and return a exception.
How can I do it ?
Exception
12-13 20:11:26.300 32356-430/br.com.application.apppackage E/Volley﹕ [157735] BasicNetwork.performRequest: Unexpected response code 400 for http://www.aplication.com.br/ServiceEndpointRest/WsChat/ws/salas/interact.json
12-13 20:11:26.305 32356-32356/br.com.application.apppackage E/ERROR METHOD:﹕ receiveMessage in ChatDAO: null
I'm trying this.
ApplicationController
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private File mImageFile;
private Map<String, Object> imageParams;
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
public Map<String, String> getHeaders() throws AuthFailureError {
headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BasicAuthenticationRest.USERNAME, BasicAuthenticationRest.PASSWORD);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
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) {
listener.onResponse(response);
}
}
#Override Header in Method receiveMessage
public ApplicationController receiveMessage(String emailAdversario){
///{\"Sala\":{\"usuario\":\"%#\",\"adversario\":\"%#\",\"atualizacao\":\"%#\",\"device\":\"%#\",\"device_tipo\":\"ios\"}}
urlPost.append("WsChat/ws/salas/interacao.json");
HashMap<String, String> params = new HashMap<String, String>();
params.put("usuario", BatalhaConfigs.USUARIO_EMAIL);
params.put("atualizacao", new Date().toString());
params.put("email", BatalhaConfigs.USUARIO_EMAIL);
params.put("device", AndroidReturnId.getAndroidId());
params.put("device_tipo", "android");
ApplicationController apc = new ApplicationController(Request.Method.POST,
urlPost.toString(),
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
Log.i("RESPOSTA DA MENSAGEM: ", obj.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "receiveMessage in ChatDAO: " + arg0.getLocalizedMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BatalhaConfigs.USUARIO_EMAIL, BatalhaConfigs.USUARIO_SENHA);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
}};
return apc;
}