Pass parameters to volley with the PUT method - java

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.

Related

Problem in using a custom header to all my Volley requests

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.

Android Volley unable to get data in response

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.

Volley GET JsonObjectRequest with JSONObjectParameter doesn't work at all

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.

How do i use a variable outside the onResponse in Android?

I have created an activity in which i insert some records into a mysql database. I declared a global variable named lastInsertId. When i try to println the variable inside the onResponse method, works fine but when i try to println outside the method returns null. I need to use this variable also outside the method. What can be done?
Here is my code:
String insertUrl = "http://localhost/file.php";
String lastInsertId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
lastInsertId = response.toString();
System.out.println(lastInsertId); // returns the lastInsertId
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
// parameters
return parameters;
}
};
requestQueue.add(request);
System.out.println(lastInsertId); // get's null
}
Thanks!
They are different results because although you are firing your request to your local HTTP server, your last println fires BEFORE you set the lastInsertId.
You need to think multi-threaded. Your HTTP request is running in the background and the UI thread is continuing. So the order of execution is not in the order the code appears in your sample.
Request queue created
Request created
Request added to queue (presumably starting HTTP call also)
Prints out lastInsertId (null)
lastInsertId is set from your response
Prints out lastInsertId
user a setter method of your variable inside onResponse
This is happening because the lastInsertId is getting declared, but never initialized,
then the StringRequest request is using a callback through anonym interfaces to print the value, that is happening asynchronous way, but your code is going forward and tryinh to print the value before that happens.
you don net extra setters o getters, you need to validate / that the string is not empty, OR only print its value inside that callack.
I figure it out. I answered this question after about a year, beacuse i saw that this post had a few hundred visitor. Hope my answer will help other feature visitors to get data out from onResponse method. Here is the code:
String insertUrl = "http://localhost/file.php";
String lastInsertId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
lastInsertId = response.toString();
System.out.println(lastInsertId); // returns the lastInsertId
callback.onSuccess(lastInsertId);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
// parameters
return parameters;
}
};
requestQueue.add(request);
}
public interface VolleyCallback{
void onSuccess(ArrayList<Data> dataArrayList);
}
And this is the code we need inside the Activity.
public void onResume(){
super.onResume();
getString(new VolleyCallback(){
#Override
public void onSuccess(String result){
System.out.println(result); // returns the value of lastInsertId
}
});
}

Get request out of onResponse

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?

Categories

Resources