I want to make an Auth header for ALL my Volley requests
I have learnt how can I create a header overriding the getHeaders of the request class but I can not change it from every request from time to time and want to make it sort of static or global where I can change it and it changes everywhere. Here is what I have tried so far.
Main activity class
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
JsonObjectRequest jsonreq;
JSONObject object;
try{
requestQueue = Volley.newRequestQueue(MainActivity.this);
object=new JSONObject();
jsonreq=new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
res=response.toString();
Log.d("log1","res : " + res);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("log1","Error from response : " +error.networkResponse.statusCode);
}
}) {
//want to get rid of this function from here and create in a global scope so I can control its implementation everywhere
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params=new HashMap<String,String>();
params.put("Authorization","xxxxxxxx");
return params;
}
};
requestQueue.add(jsonreq);
}
catch (Exception e){
Log.d("log1","error from catch " + e);
return e.toString();
}
return res;
I tried making a custom class that extends HurlStack and override the execute request. Here is the code for custom HurlStack class called GlobalHeaders
public class GlobalHeaders extends HurlStack {
String testing="xxxxxxxx";
#Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
Map<String, String> headers = request.getHeaders();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization",testing);
return super.executeRequest(request, headers);
}
Now I am not sure how can I make use of this method in my main class where I am adding the requestQueue(jsonReq);
I tried other way were I override Request class of Volley with my custom class but again failed.
Please point how can I make this work or any other approach. I am a new learner to Java and Android.
Ok I have tried and this solution seems to work out. Posting here so It may also help someone in future.
Removed the getHeader method from the Main activity as the execute request gets called itself when I added its instance into the request using the below code.
if(stack == null){
stack=new GlobalHeaders();
requestQueue=Volley.newRequestQueue(getApplicationContext(),stack);
requestQueue.add(jsonreq);
}
Also need to change the first line in executeRequest method to cater the null exception to following
Map<String, String> headers = new HashMap<>(additionalHeaders);
and keep the return statement unchanged.
Related
Am trying to send http request using volley but am receiving error
javax.net.ssl.SSLHandshakeException: Connection closed by peer
I google around and try some suggestions but none solve my problem. please help
Bellow is the code am using
public class volley {
static RequestQueue queue=null;
public static String TAG = "MY_VOLLEY";
volley(final String URL,
final String Text
final Context context
){
helper.log(TAG,"Started Loading");
// Instantiate the RequestQueue.
if(queue==null) {
queue = Volley.newRequestQueue(context);
}
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(
Request.Method.POST, URL, new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
return;
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
try {
params.put("message",Text);
params.put("from",From);
} catch (Exception e) {
helper.log(TAG, "Error, hash map failed");
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
return;
}
}
In terms of debugging the JSSE is a pain in the ...
Most likely the handshake fails and JSSE most of the time only shows you the final problem, i.e. that the server is closing the connection. Quite often the server is telling you the problem in an TLS alert message but that doesn't show up in the exception message.
If you have Wireshark or something similar installed, the easiest way is to fire up a session and look at the TLS-records (Wireshark shows them quite nicely so it's easy to recognize the error-packet containing the error-code and meaning).
If you don't have that tool, yet, you can activate SSL-debugging and look at the messages on STDOUT. Be warned that they are a bit hard to read if you're unfamiliar with TLS and - since it's a global setting - you should make sure that your tests happens when no other TLS-connection is established, otherwise you get mixed outputs. To enable TLS-handshake debugging, set the system property -Djavax.net.debug=ssl:handshake
I am trying to make a web-service call using volley and printing the response in the logcat. But I don't know why I am not getting response. Not even any error message.
Below is my code. I know I am missing something. Please correct me.
private void syncData() {
mProgressDialog.showProgressDialog("Initializing Please Wait...");
RequestQueue requestQueue = Volley.newRequestQueue(SalesDashboard.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, SYNC_DATA_SALES, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.dismissProgressDialog();
Log.e("TAG", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismissProgressDialog();
Log.e("TAG", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String , String> params = new HashMap<>();
String userrole = mSessionManagement.getLoggedInUser().get(SESSION_USER_ROLE);
params.put("branch", mSessionManagement.getSelectedBranch());
params.put("staff_id", mSessionManagement.getLoggedInUser().get(SESSION_EMP_ID));
params.put("user_role", mSessionManagement.getLoggedInUser().get(SESSION_USER_ROLE));
params.put("user_dept", mSessionManagement.getLoggedInUser().get(SESSION_DEPT_IDS));
params.put("principal", mSessionManagement.getLoggedInUser().get(SESSION_PRINC_IDS));
if (userrole.equals(ADMIN) || userrole.equals(COUNTRY_MANAGER)) {
params.put("user_div", mSessionManagement.getSelectedDivision());
} else {
params.put("user_div", mSessionManagement.getLoggedInUser().get(SESSION_DIV_IDS));
}
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
I am not receiving any error message also or any kind of exception. I have checked the webservice by hitting it on browser the response is displayed correctly on the browser but not able to fetch it in android.
Why you call super.getParams() on return instead params? Maybe it turn wrong on your request. Then try as follow
#Override
protected Map<String, String> getParams() throws AuthFailureError {
...
return params;
}
Bonus: use getMessage instead do toString() your error object
Print the stringRequest and check the url and cross verify with ur url
Before that check have u added Internet permissions in manifest file.
I've got a problem with Volley request - I want to send GET (another similiar POST also) request with JSONObject param (user having password and login) to authorize user and send back full user data. Although I can see during debugging that mRequestBody is correct JSON but I cannot receive it by my controller -
private void processLogin() throws JSONException {
this.user.setLogin(this.loginText.getText().toString());
this.user.setPassword(this.passwordText.getText().toString());
final JSONObject jsonObject = new JSONObject(new Gson().toJson(this.user));
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, UrlHelper.loginUrl, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
user = new Gson().fromJson(response.toString(), User.class);
if (user.getUserId().equals(getResources().getString(R.string.ERROR))) {
onLoginFailed();
} else {
onLoginSuccess(user);
}
}
}, 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, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(request);
}
Controller method:
#RequestMapping(value = "/loginTest", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public User someMethod(#RequestBody User user) throws SQLException {
return userService.authenticateUser(user.getLogin(), user.getPassword());
}
Without annotation #RequestBody I it process but User in param is empty, so I process User with null password and login. Recently I did it by StringRequest Please, help me. :)
As a part of the HTTP specs, GET requests have no body. You can create and send GET requests with a body though, but that's meaningless since the body has no semantic meaning in the GET method specification. I don't know too much about Spring, but my guess is that Spring is probably ignoring the body of the request because it's a GET method. You should send and receive the request as POST if your intention is to put something inside the body.
I'm using this simple code :
JsonObjectRequest req = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
delegate.postNotificationSucced();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d(TAG, ""+error.getMessage()+","+error.toString());
delegate.postNotificationFailed((APIErrors) error);
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/x-www-form-urlencoded");
headers.put("state", Boolean.toString(isChecked));
return headers;
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError){
APIErrors error = null;
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
error = new APIErrors(new String(volleyError.networkResponse.data));
}
return error;
}
};
When I use the Request.Method.GET or POST instead of PUT, the getParams() method is called but not with the PUT method.
My problem is that my API requires a PUT method.
How can I pass my parameters using the PUT method.
Edit :
With the PUT method the getHeaders() method is called, so can I pass my arguments through it ?
Solution :
In my case I solved the problem changing my JsonObjecRequest to StringRequest like suggested by #ishmaelMakitla. And now I pass inside getParams().
I noticed that you are not using the response object for anything - so
perhaps change the request from JsonObjectRequest to a StringRequest -
remember that you then need to change Response.Listener()
to Response.Listener() and the onResponse(JSONObject response)
to onResponse(String response)....shout if you need further help. I
hope this leads to some workable solution.
The reason is that with JsonObjectRequest, parameters must be pass through the third parameters of the constructor
jsonRequest - A JSONObject to post with the request. Null is allowed
and indicates no parameters will be posted along with request.
you can read the doc for more informations.
Since you are not using the response object for anything - you should change the request from JsonObjectRequest to a StringRequest - remember that you then need to change Response.Listener<JSONObject>() to Response.Listener<String>() and the onResponse(JSONObject response) to onResponse(String response).... here is StringRequest Gist I created - you can simply "plug-and-play" in your code and replace the JsonObjectRequest code.
I have a method that does a GET request using Volley Library
public void get(String 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) {
System.out.println("Successfull response is: " + response);
}
}, createMyReqErrorListener()) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(ACCEPT, ACCEPT_JSON);
headers.put(AUTH_ID, AUTH_ID_VALUE);
headers.put(PLATFORM, PLATFORM_VALUE);
headers.put(CID, "");
System.out.println(headers.toString());
return headers;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
In the onResponse Override method i would like to get the response object passed onto my parser which is in a data class, which will then pass the parsed info (images/name etc) to the activity so it can display it?
How could i pass the object up the chain?