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.
Related
Is okhttp is good for this or do you have any code similar to this ping me
Posting Data To server By Get Method
public void sendingDataToServer(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponseSuccess", response.toString() + "check");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onResponseSuccess", error.toString() + "check");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; ");
headers.put("x-oc-Image-url", "Your Image Path Url");
try {
headers.putAll(super.getHeaders());
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
return super.getHeaders();
}
};
Volley.newRequestQueue(mContext).add(stringRequest);
}
If Your Sending Only Url to server there are ways to send Image Url to server
1. Passing through Header
2. Passing through JsonObject
I Suspect their is not posting Image Url path in your code.
In Server Side 500 error means request parameter not receiving to server time you will get this error.
I had 2 pages: first one is login page and second is category page. In login API after entering the credentials, I am getting the response as sesssion id from response header.
The sesssion id will be saved and it will use for further API calls. I am trying to call second API (category page). In this page, as an input am passing the saved session id in the request header. Getting response as "session expired". Also tried to pass Set-Cookie: PHPSESSID=d9f9sdkfjs9 in the request header. but it didn't work.
Note :
I am experiencing this issue in production environment only (SSL included)
I am using volley library for handling APIs.
public void fnCallLoginAPI() {
try {
//DEMO URL
//final String URL="http://demo.io/api/api.php?m=login";
//LIVE URL
final String URL = "https://www.live.com/shop/api/api.php?m=login";
final String requestBody = "email=abc.b#xyz.com" + "&password=43443==" + "&strPlatform=i" + "&strDeviceToken=null";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie", "PHPSESSID=" + sessionID);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
System.out.println("THE REQIEST BODY IS" + requestBody);
body = requestBody.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("TAG", "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {
}
}
public void fnCallCateGoryAPI(){
try { final String URL ="https://www.live.com/shop/api/api.php?m=getcategories";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(strResponse);
sessionID = jsonObj.optString("session_id");
System.out.print("sessionID" + sessionID);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {}
}}
#fazil try after increasing the token expiration time from the backend
#fazil : I was facing something similar in my projects too and the reason i understood was actually due to multiple header values set under same key "Set-Cookie".
Please do check this in your logs.
Also, make sure that you have set the headers properly in your request(check the logs of request and response from your Server).
If everything implemented is correct and the issue is due to multiple values in the same header you need to check this implementation of volley : https://github.com/georgiecasey/android-volley-duplicateheadersfix
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);
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);
I am trying to call a RESTful API in my Android app using Volley. The API requires that the user get authenticated using a public key and a hash that will be sent via the http header.
When I try to do send a POST request with the headers of the public key and the hash, I find that the header is not appended / received by the server and I get Volley error - BasicNetwork.performRequest: Unexpected response code 400
This is the method that i am trying to use to send the header request with the request parameters using JSON.
HashMap<String, String> params = new HashMap<String, String>();
params.put("email", email.getText().toString());
params.put("password", password.getText().toString());
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Logging in...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(ApplicationConstants.url_sign_in, new JSONObject
(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "onResponse") ;
error = response.getBoolean(TAG_ERROR);
message = response.getString(TAG_MESSAGE);
Toast.makeText(LoginActivity.this, message + " value of error", Toast.LENGTH_LONG).show();
pDialog.cancel();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,"onErrorResponse()") ;
pDialog.cancel();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED) {
// HTTP Status Code: 401 Unauthorized
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(ApplicationConstants.publicKey, "Yahoo");
headers.put(ApplicationConstants.hash, "Google");
Log.d(TAG,"getHeaders()") ;
return headers;
}
};
requestQueue.add(request);
ApplicationConstants class
public interface ApplicationConstants {
//String ip = "10.0.3.2";
String ip = "192.168.100.2";
String publicKey = "pskPublicKey";
String hash = "pskPublicKey";
If I try this with only the request parameters it works but when when i try to send a header request it fails to send the header request.
As you can see in the pic I supplied the public key and the hash in postman and I also sent data in the header from android but it is not being received in the server
400 means a Bad Request to the server. Maybe the headers are wrong.
You could try adding the Content-Type=application/json header as follows
header.put("Content-Type", "application/json");
If this doesn't work then you should try the request in the REST client and see if it works with the given headers. Make sure the request works fine on the rest client before trying to break your head in Android.
override your getBodyContentType method
public String getBodyContentType()
{
return "application/json";
}