Android JSON request with Volley - java

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

Related

E/Volley: [2342] NetworkUtility.shouldRetryException: Unexpected response code 400

I'm using the Android volley library and I'm trying to sending data to the API server but it responds to this error every time
E/Volley: [2342] NetworkUtility.shouldRetryException: Unexpected response code 400 for API
This is my code:
JSONObject params = new JSONObject();
try {
params.put("deptcode", 649);
params.put("endDt", "2021-07-22T12:37:28.755Z");
params.put("instCode", 152);
params.put("instSesNO", 0);
params.put("locCode", 2);
params.put("observedBy", obserName);
params.put("sessionId", 0);
params.put("startDt", "2021-07-22T12:37:28.755Z");
params.put("status", "string");
}
catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(300000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyRequestQueue.add(jsonObjReq);
I tried many ways but still doesn't work for me. Please help me.
normally 400 is a server error that is something not found on server.
1- try your api on postman and verify it is working.
2- sometimes, the value we're passing in int can be resolved by converting them to string.
3- try to get the error message from error.getMessage().
if not resolved, please share your api i'll check.

Android can not send post request with volley(BasicNetwork.performRequest: Unexpected response code 404)

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

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.

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