volley Unexpected response code 400 particular json response - android

I am using volley JsonObjectRequest, I getting json response for some json format and getting 400 response code for some format.
Json format
{
"errors": "This password is too short. It must contain at least 8 characters & Please provide a valid id type",
"message": "Account could not be created with received data.",
"status": "Bad request"
}
volley call
public void userRegistraion(String identifier, String password, String idType){
final String URL = "https://someweb.com/auth/user/registration/";
//Post params to be sent to the server
JSONObject params = new JSONObject();
try {
params.put("identifier", identifier);
params.put("password", password);
params.put("id_type", idType);
}catch (JSONException e){
e.printStackTrace();
}
JsonObjectRequest request_json = new JsonObjectRequest(Request.Method.POST,URL,params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("volley response",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("volley", "Error: " + error
+ "\nStatus Code " + error.networkResponse.statusCode
+ "\nResponse Data " + error.networkResponse.data
+ "\nResponse header " + error.networkResponse.headers
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
// add the request object to the queue to be executed
Myapplication.getInstance().addToRequestQueue(request_json);
}
Error:
E/Volley: [74123] BasicNetwork.performRequest: Unexpected response code 400 for https://someweb.com/auth/user/registration/
but no error is coming for this json type with the same request.
{"user":{"th_user_id":"KSJDYDYD",
"is_active":true,
"is_verified":false,
"role":"user",
"created_at":"2018-03-21T06:25:02.556490Z",
"updated_at":"2018-03-1T06:25:02.556516Z",
"verified_at":null,"last_login":"2018-03-21T06:25:02.570251Z",
"documents":[]},
"token":"11f2faea30847db4u3hfhu0384hh392dac46"}

The 400 Bad Request error is an HTTP status code that means that the JsonObjectRequest request you sent to the api endpoint in your server was incorrect or corrupted and the server couldn't understand it.
I would suggest you let your php file report all error like this so that you get more information about this error
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Related

Client Error trying to do JsonObjectRequest with Android Volley

I'm trying to do an HTTP PUT with JSON to a service that needs HTTP Basic Auth, but I keep getting client errors. I do this:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, payOp.getURL(), payOp.getJson(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("jsonObjectRequest", "Response " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("jsonObjectRequest", "Error " + error.toString());
Log.i("jsonObjectRequest", "Error ", error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
ApplicationSettings applicationSettings = ApplicationSettings.getInstance();
String username = applicationSettings.mMID;
String password = applicationSettings.mAPIPassword;
String creds = String.format("%s:%s",username, password);
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
Log.i("jsonObjectRequest","Authorization is: " + auth);
params.put("Authorization", auth);
return params;
}
};
queue.add(jsonObjectRequest);
And I get back:
2019-05-04 17:52:40.158 7430-7430/com.amex.gatewaydemotr5 I/jsonObjectRequest: Error
com.android.volley.ClientError
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:199)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)
I can't figure out what I'm doing wrong. I'm making the creds string correct (I have another app written in node.js that works to compare the output to) but I don't get a lot of output from Volley for an error. Can anyone see what I'm doing wrong? Is there some way to get more detail out of Volley on the error? Thanks!
Ok, figured it out. It was a problem with my URL & Data, but the main thing was I didn't understand how to parse the errors, for anyone who needs to know there's a networkResponse object on the error that has statusCode and data parameters. The server messages are there. The data parameter comes back as a byte array, so you have to wrap it in a string object to see the results.
Once I understood that I could get the messages back I needed and fix the problem, here's the code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, payOp.getURL(), payOp.getJson(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("jsonObjectRequest", "Response " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("jsonObjectRequest", "Error, Status Code " + error.networkResponse.statusCode);
Log.i("jsonObjectRequest", "URL: " + payOp.getURL());
Log.i("jsonObjectRequest", "Payload: " + payOp.getJson().toString());
Log.i("jsonObjectRequest", "Net Response to String: " + error.networkResponse.toString());
Log.i("jsonObjectRequest", "Error bytes: " + new String(error.networkResponse.data));
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
ApplicationSettings applicationSettings = ApplicationSettings.getInstance();
String username = applicationSettings.mMID;
String password = applicationSettings.mAPIPassword;
String creds = String.format("%s:%s",username, password);
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
Log.i("jsonObjectRequest","Authorization is: " + auth);
params.put("Authorization", auth);
return params;
}
};
The important part is this:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("jsonObjectRequest", "Error, Status Code " + error.networkResponse.statusCode);
Log.i("jsonObjectRequest", "URL: " + payOp.getURL());
Log.i("jsonObjectRequest", "Payload: " + payOp.getJson().toString());
Log.i("jsonObjectRequest", "Net Response to String: " + error.networkResponse.toString());
Log.i("jsonObjectRequest", "Error bytes: " + new String(error.networkResponse.data));
}

500 exception while connecting to live server using Volley in android

I'm trying to connect to live server using volley authentication and sending values through POST method. It worked well when connected to local server but I'm getting the below exception when connecting to live server.
BasicNetwork.performRequest: Unexpected response code 500 for "URL"
And server side error is below
Error parsing media type 'application/json; charset=utf-8, application/x-www-form-urlencoded; charset=UTF-8' Expected separator ';' instead of ',' This is the error getting in server side
Here is my code
public void userLogin(){
showDialog(DIALOG_LOADING);
final String json = new Gson().toJson(arr);
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
Const.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("LOGIN Response :" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
System.out.println("NetworkResponse "+ networkResponse);
if (networkResponse!= null && networkResponse.statusCode == 401) {
Login.this.runOnUiThread(new Runnable() {
public void run() {
invalidemail.setVisibility(View.GONE);
inactiveaccount.setVisibility(View.VISIBLE);
}
});
}
error.printStackTrace();
removeDialog(DIALOG_LOADING);
toast_tv.setText("There is no Internet connection. Try again...!");
toast.show();
}
}){
#Override
public byte[] getBody() {
try {
return json == null ? null : json.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
json, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String credentials = String.format("%s:%s",Const.auth_username,Const.auth_password);
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
headers.put("Content-Type", "application/json; charset=utf-8");
return headers ;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 0, 0));
Volley.newRequestQueue(this).add(jsonObjReq);
}
On the server side Jersey is being used with Java.
Finally I fixed the issue.. Actually nothing wrong in code but the volley version which i used was deprecated. When updating the volley library it worked for me.

How to make XML api request with header, body and params?

I am following using https://gist.github.com/itsalif/6149365 library for making XML requests.
It uses Simple-XML for serialising XML to Objects.
I am able to make XML request successfully when there is no header and parameters associate with the SOAP api. However I am unable get response while performing little complex request which consist of header and parameters.
My request format looks like this
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.holidaywebservice.com/HolidayService_v2/">
<SOAP-ENV:Body>
<ns1:GetHolidaysAvailable>
<ns1:countryCode>UnitedStates</ns1:countryCode>
</ns1:GetHolidaysAvailable>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Code
HashMap<String, String> mapData = new HashMap<>();
final String mRequestBody = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://www.holidaywebservice.com/HolidayService_v2/\">\n" +
" <SOAP-ENV:Body>\n" +
" <ns1:GetHolidaysAvailable>\n" +
" <ns1:countryCode>UnitedStates</ns1:countryCode>\n" +
" </ns1:GetHolidaysAvailable>\n" +
" </SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>";
SimpleXmlRequest dellaRequest = new SimpleXmlRequest<String>
(Request.Method.POST, "http://www.holidaywebservice.com//HolidayService_v2/HolidayService2.asmx?wsdl", String.class, headerDataMap, bodyDataMap,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("BaseActivity", "response = " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("BaseActivity", "Error:" + error.getMessage());
}
}
){
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, "utf-8");
return null;
}
}
};
I am getting 400 response code i.e. BAD REQUEST, state that invalid input is provided e.g validation error or missing data.
This api working fine in Postman rest client. So I am not able to figure out what am I doing wrong.
You can use Volley to call this XML request effectively.
String url = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx";
//Volley request
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
}) {
#Override
public String getBodyContentType() {
// set body content type
return "text/xml; charset=UTF-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return reqXML.getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
// TODO consider if some other action should be taken
return null;
}
}
};
//
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(request);

Adding headers to jsonArrayRequest using Volley Android

I want to send jsonArray and also some header with it to the server using Volley. I have used the following way:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.POST, URL, jsonParams, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d( LOG_TAG, "JSON response: " +response );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d( LOG_TAG, "Error data: " + error.toString());
String errorResponse = Arrays.toString( error.getStackTrace() );
Log.d( LOG_TAG, "Volley response: " + errorResponse);
Log.d( LOG_TAG, "Network response: " +error.networkResponse.statusCode );
Log.d( LOG_TAG, "Volley error: " + error.getMessage()+"\n"+ Log.getStackTraceString( error ));
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap < String, String > headers = new HashMap<>();
headers.put( USER_TOKEN, mUserToken );
return headers;
}};
Here, I am getting status code as 405, on hitting the URL.
I want to send a user token as a header along with the jsonArray but unsuccessful.
jsonParams is json Array that can contain one or multiple json objects.
Can anybody guide me for what is the correct way of adding headers or any other solution?
When you get 405 status code from server means that you are sending wrong method to server. In short POST method need to be GET method vice versa.

Using Android Volley with ASP .NET Web API

I am trying to retrieve a resource from my asp .net restful service from an android client.
I have a MessagesController which has the method GetMessages:
[Authorize]
public IQueryable<Message> GetMessages()
{
return db.Messages;
}
To access this I have sent a request to /token and have obtained a key which I use from the client application to access the resource.
The trouble I have is that the client is receiving a 302 http error when trying to access the resource.
This is the method in the android client:
public void setAllSendersAndAllMessages()
{
String url = "Messages/GetMessages";
showpDialog();
String Url = baseUrl + url;
JsonArrayRequest req = new JsonArrayRequest(Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
allSenders = new String[response.length()];
allMessages = new String[response.length()];
for (int i = 0; i < response.length(); i++) {
JSONObject message = (JSONObject) response.get(i);
allSenders[i] = message.getString("sender");
allMessages[i] = message.getString("messageContent");
}
setInitialViews();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(context,error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "bearer "+ token);
return headers;
}
};
mRequestQueue.add(req);
}
I am overriding the getHeaders() method to send the authorization token to the service. This key and header works perfectly when using 'Postman' but fails in the android client for some unknown reason.
If anyone can offer some advice it would be greatly appreciated!
HTTP 302 is URL error, URL must be like :
http://server/WepApi/api/orders
Server : Your IIS server Name , or Your server IP address

Categories

Resources