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?
Related
I am trying to register some data with an api and I have checked the json that I get in my application and the structure and data are fine, I put it in Postman and it works fine, the url is also fine, someone could help me to know what I am doing wrong ?
this is the method with which I try to make the call to the api
private void request2(final String json){
// Instantiate the RequestQueue.
RequestQueue mRequestQueue = SingletonRequestQueue.getInstance(getApplicationContext()).getRequestQueue();
// Request a string response from the provided URL.
StringRequest stringRequestPOSTJSON = new StringRequest(Request.Method.POST, BASE_URL + "/api/Asociado/RegistrarAsociado", new Response.Listener() {
#Override
public void onResponse(Object response) {
// response..
}
}, errorListener) {
#Override
public Priority getPriority() {
return Priority.HIGH;
}
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Authorization", "Bearer "+ bearertoken);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = json; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequestPOSTJSON);
}
This is the error I get: E/Volley: [4146] BasicNetwork.performRequest: Unexpected response code 400 for
try this code:
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
I have an Android app which calls web services using Volley. If my app is being opened and I manually change the time (backward or forward), Volley is not triggering new requests and the response which is already in the cache is returning. If I clear cache and data, only then the new request will trigger and new response will appear. How the Volley requests are related to system time and why this is happening? Is there any solution for this?
StringRequest stringRequest = new StringRequest(Request.Method.POST, new ServiceUtils().url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d(TAG, "onResponse: response " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.d(TAG, "onErrorResponse: " + error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("parm1", parm1);
nameValuePairs.put("parm2", parm2);
nameValuePairs.put("parm3", parm3);
return nameValuePairs;
}
};
addToRequestQueue(stringRequest, "", getApplicationContext());
Volley caches any request automatically and to overcome this situation, you need to set the setShouldCache attribute to false.
request.setShouldCache(false);
myQueue.getCache().clear();
myQueue.add(request);
Here's a full request copied from the Github issue.
RequestQueue queue = Volley.newRequestQueue(context);
queue.getCache().clear();
StringRequest myReq = new StringRequest(Request.Method.POST,
VolleyConnector.url,
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Cn","1");
params.put("Yr","1396");
params.put("MaxInPage","10");
params.put("Method","Control_Vaziat_View");
params.put("Pg","1");
return params;
};
};
myReq.setShouldCache(false);
queue.add(myReq);
Hope that helps!
I am trying to send some info to my api with post method(volley), but keep getting errors. Most consistent and the latest one is
E/Volley: [1449] BasicNetwork.performRequest: Unexpected response code 404 for http://....
D/Error.Response: com.android.volley.ClientError
I am able to post it with postman but not in android. I am sure nothing is wrong in the other side. I don't know what to do.
I have tried several implementations with getheader(),getBodyContentType(), Json object, string, parsing, try catch and so on..
RequestQueue queue = Volley.newRequestQueue(this);
String url = "....";
StringRequest postRequest = new StringRequest(Request.Method.POST, 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) {
// error
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
Log.d("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", "test#email.com");
params.put("token", "token");
return params;
}
};
queue.add(postRequest);
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.