Getting BasicNetwork.performRequest: Unexpected response code 400 in Volley - android

In My Activity it Checks the user credentials and returns session id and related info if valid. The Method is POST.The parameter has to send as JSON.
{
"params": {
"context": {},
"db": "testing",
"login": "admin",
"password": "admin"
}
}
So i create a JSONObject and send it as it is With Header.I am getting response in POSTMAN.But what i m getting error when i call it as it is.Can Any one help me in this?
private void volleyLogin() throws JSONException {
mProgressView.setVisibility(View.VISIBLE);
JSONObject one = new JSONObject();
one.put("context",new JSONObject());
one.put("db","testing");
one.put("login","admin");
one.put("password","admin");
JSONObject params = new JSONObject();
params.put("params",one);
HashMap<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json; charset=utf-8");
RequestQueue requestQueue = Volley.newRequestQueue(this);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST,
ApiConstants.URL_AUTHENTICATE,params,header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response"+response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("VolleyError"+error);
}
}
);
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(120),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
System.out.println("jsObjRequest"+jsObjRequest);
requestQueue.add(jsObjRequest);
}
Here is the Custom Request Class
public class CustomRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private JSONObject jsonObjectParams;
private Map<String, String> headers;
public CustomRequest(int method,String url, JSONObject jsonObjectParams,Map<String, String> headers,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.jsonObjectParams = jsonObjectParams;
this.headers= headers;
System.out.println("method"+method);
System.out.println("url"+url);
System.out.println("jsonObjectParams"+jsonObjectParams);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
volleyError = error;
}
return volleyError;
}
}

You can try something like this:
Create a singletone class VolleyDispatcher, that holds the RequestQueue from volley.
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return requestQueue;
}
/**
* Recreates the request queue using username/password https auth.
*/
public void recreateRequestQueue() {
if (!AppUtil.isEmpty(AppConstants.USERNAME) && !AppUtil.isEmpty(AppConstants.PASSWORD)) {//check if a user is logged in so that the https auth can be created if necessary
if (requestQueue != null) {
requestQueue.stop();
requestQueue = null;
}
requestQueue = Volley.newRequestQueue(mContext.getApplicationContext(), new HurlCustomStack());
}
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
Call recreateRequestQueue before doing any volley requests
Implement the custom HurlStack
public class HurlCustomStack extends HurlStack {
#Override
protected HttpURLConnection createConnection(URL url) throws IOException {
// Workaround for the M release HttpURLConnection not observing the
// HttpURLConnection.setFollowRedirects() property.
// https://code.google.com/p/android/issues/detail?id=194495
// connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects());
return HttpUrlConnectionHelper.getInstance().createHttpUrlConnection(url);
}
}
And the client creation method:
public HttpURLConnection createHttpUrlConnection(URL url) throws IOException {
Log.d(TAG, "Create http url connection with url : " + url.toString());
HttpURLConnection httpConnection = null;
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
httpConnection = https;
} else {
httpConnection = (HttpURLConnection) url.openConnection();
}
httpConnection.setReadTimeout(TIMEOUT);
httpConnection.setConnectTimeout(TIMEOUT);
String basicAuth = "Basic " + new String(Base64.encode((AppConstants.USERNAME + ":" + AppConstants.PASSWORD).getBytes(), Base64.NO_WRAP));
httpConnection.setRequestProperty("Authorization", basicAuth);
httpConnection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
return httpConnection;
}
So now, every time you want to make a request, just use the addToRequestQueue method in the VolleyDispatcher class.

Related

Volley POST Request with headers and raw json body

I am trying to make Post request from Android App that takes username and password in request body with content-type application/json in headers.
I tried changing content-type and how i send username passoword in body, but still no luck
public class MainActivity extends AppCompatActivity {
private Button Login;
private EditText loginEmail, loginPassword;
String URL = "https://localhost:8080/api/v1/auth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginEmail = (EditText)findViewById(R.id.etUsername);
loginPassword = (EditText)findViewById(R.id.etPassword);
Login = (Button)findViewById(R.id.btnLogin);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", loginEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String requestBody = jsonObject.toString();
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, LandingPage.class));
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Toast.makeText(MainActivity.this, res, Toast.LENGTH_LONG).show();
Log.i("MainActivity", res);
//use this json as you want
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
}
});
}
}
Post Request from Postman works perfectly fine but it throws Error 400 with Volley.
Below is the error I get in console
"errorSummary":"Bad request. Accept and/or Content-Type headers likely do not match supported values."
Try using a custom request and extending Request<JSONObject>:
CustomRequest class:
public class CustomRequest extends Request<JSONObject> {
private final Map<String, String> mHeaders;
private final JSONObject mBody;
private final Response.Listener<JSONObject> mResponseListener;
public CustomRequest(int method, String url, Map<String, String> headers, JSONObject body, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mHeaders = headers;
this.mBody = body;
this.mResponseListener = responseListener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return mHeaders != null ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "application/json; charset=UTF-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
return mBody != null ? mBody.toString().getBytes(Charset.forName("UTF-8")) : super.getBody();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mResponseListener.onResponse(response);
}
}
Usage:
String url = "https://localhost:8080/api/v1/auth";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", loginEmail.getText().toString());
jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
CustomRequest customRequest = new CustomRequest(Request.Method.POST, url, headers, jsonObject, response -> {
// put your reponse listener code here
}, error -> {
// put your error listener code here
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(customRequest);

How to put Cookie session id into volley request?

So, i have this code to make a POST request with volley:
public class MainActivity extends AppCompatActivity {
Button btnSearch;
ProgressDialog loadingDialog;
ListView lvResult;
String session_id;
RequestQueue queue;
MyCookieManager myCookieManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch = (Button) findViewById(R.id.btnSearch);
lvResult = (ListView) findViewById(R.id.lvResult);
loadingDialog = new ProgressDialog(MainActivity.this);
loadingDialog.setMessage("Wait.\nLoading...");
loadingDialog.setCancelable(false);
myCookieManager = new MyCookieManager();
requestCookie(); //FIRST CALL TO GET SESSION ID
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showLoading();
requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
}
});
}
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
//
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap < String, String > ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
//"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
return params;
}
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(postRequest);
}
public void requestWithSomeHttpHeaders() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
Log.d("Response", response);
String x = myCookieManager.getCookieValue();
String status = "";
try {
JSONObject resultObject = new JSONObject(response);
Log.d("JSON RESULT =>", resultObject.toString());
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
hideLoading();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map <String, String> getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap <String, String> ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
return params;
}
};
queue.add(postRequest);
}
private void showLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!loadingDialog.isShowing())
loadingDialog.show();
}
});
}
private void hideLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
});
}
}
If I send a valid cookie ID this return a valid JSON object else a empty object.
I tried (unsuccessfully) to set default cookie handles like
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
but I get a empty object.
How to put a valid cookie session ID to post request?
So the problem was getting a valid cookie. My mistake was to get it from the POST request itself. I kept the same working principle, getting the cookie when I started the application but using GET instead of POST and calling the root of the URL instead of the address where I get the JSON.
My solution looked like this:
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(getRequest);
}
Using cookies with Android volley library
Request class:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* #param method
* #param url
* #param params
* A {#link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* #param listener
* #param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
#Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* #see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* #see com.android.volley.Request#getHeaders()
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
MyApp:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
#Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* #param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.
for getting cookie from login request
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
CookieManager cookieManage = new CookieManager();
CookieHandler.setDefault(cookieManage);
progressDialog.hide();
try {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
Log.e("session", sessionId);
Log.e("responseString", responseString);
JSONObject object = new JSONObject(responseString);
CustomStringRequest class
public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {
private Response.Listener<CustomStringRequest.ResponseM> mListener;
public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = responseListener;
}
#Override
protected void deliverResponse(ResponseM response) {
this.mListener.onResponse(response);
}
#Override
protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
ResponseM responseM = new ResponseM();
responseM.headers = response.headers;
responseM.response = parsed;
return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
}
public static class ResponseM {
public Map<String, String> headers;
public String response;
}
}
set cookie when add request to server..
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String session=sharedPreferences.getString("sessionId","");
headers.put("Cookie",session);
return headers;
}

send request and get response cookies with android volley

I made a project and using REST to send and get data from server, I used HttpURLConnection to send request
then I've found volley that make it easier to use, but I have a problem using cookies on volley
here is my request function
public void doActionJsonPost() {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, IConstants.BASE_URL + url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(response);
String msgCode = jsonObject.getString("responseCode");
} catch (JSONException e) {
LoggingHelper.verbose(e.toString());
iHttpAsync.onAsyncFailed(e.toString());
} catch (Exception e) {
LoggingHelper.verbose(e.toString());
iHttpAsync.onAsyncFailed(e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
LoggingHelper.verbose("ERROR");
iHttpAsync.onAsyncFailed(error.getMessage());
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
iHttpAsync.onAsyncProgress();
return parameters.getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getAuthHeader(context);
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Map<String, String> responseHeaders = response.headers;
String rawCookies = responseHeaders.get("Set-Cookie");
return super.parseNetworkResponse(response);
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
I have override parseNetworkResponse to get headerResponse, but I cannot see cookies there
my question is, how can I send and get cookies from volley?
try this and pass your header in this methods
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}

Basic Authentication not working in Volley in android

I am using volley library but when I use basic authentication then I do not got any response and also volley is not showing any error. I am also try HttpUrlConnection with Asyntask but I face same problem. Please provide solution this problem.
I also hit my api via Postman client, ARC and my api is working fine with these client.
MyJsonObjectRequest.java
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {
private Priority priority = null;
//private Map<String, String> headers = new HashMap<String, String>();
public MyJsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
public MyJsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,
ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
#Override
public Priority getPriority() {
if (this.priority != null) {
return priority;
} else {
return Priority.NORMAL;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//Log.e("JSON"," AUTH CODE "+createBasicAuthHeader("MaS", "123456"));
return createBasicAuthHeader("username", "123456");
}
Map<String, String> createBasicAuthHeader(String username, String password) {
Map<String, String> headerMap = new HashMap<String, String>();
String credentials = username + ":" + password;
String encodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headerMap.put("Content-Type", "application/json; charset=utf-8");
headerMap.put("Authorization", "Basic " + encodedCredentials);
return headerMap;
}
public void setHeader(String title, String content) {
// headers.put(title, content);
}
public void setPriority(Priority priority) {
this.priority = priority;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError){
NetworkResponse response = volleyError.networkResponse;
if (response!=null)
{
Log.e("TAG"," VOLLEY ERROR1 "+response.statusCode);
}
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
Log.e("TAG"," VOLLEY ERROR "+error.toString());
volleyError = error;
}
return volleyError;
}
}
My MainActvity
public class JsonObjectActivity extends AppCompatActivity {
JsonObjectRequest gsonRequest;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_object);
textView = (TextView) findViewById(R.id.tv2);
try {
doingProcessJsonArray();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void doingProcessJsonArray() throws JSONException {
// i am use local server like
String newUrl="http://myserver:8023/Users.svc/password_encrypt";
JSONObject params = new JSONObject();
params.put("PASSWORD", "12345655");
//params.put("domain", "http://samset.info");
gsonRequest =new JsonObjectRequest(Request.Method.POST,newUrl, params, successListener(), errorListener());
Constants.showProgressDialog(this, "Loading..");
//gsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Start progressbar
// gsonRequest.setPriority(Request.Priority.IMMEDIATE);
Log.e("TAG"," request "+gsonRequest.toString());
VolleySingleton.getInstance(this).addToRequestQueue(gsonRequest, "volleyrequest");
}
private Response.ErrorListener errorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error "+error.toString());
}
};
}
public Response.Listener successListener()
{
return new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Constants.dismissDialog();
Log.e("Volley","Responce "+response.toString());
textView.setText("JSONObject RESPONCE > "+response.toString());
}
};
}
}
postman screen shot

How to rewrite my multipart post string request to json object request using volley?

I have a thread here on stack overflow, and I already solved my problem upon using a multipart post through Volley. The problem is, what I have done is a String request and I want it to be change to JSONObject request because I needed to catch the server's response.
UPADATE : I also tried to change all Response<String> to Response<JSONObject>
This is my new implementation at my parseNetworkResponse(NetworkResponse response) method :
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
{
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
But unfortunately, It started calling the error response method
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error",error.toString());
}
The error displayed is :
com.android.volley.ParseError: org.json.JSONException: Value <div of type java.lang.String cannot be converted to JSONObject
As my answer in your previous question, I suggest that you create a custom request that reponses NetworkResponse or JSONObject like the following :
MultipartRequest.java:
class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return mMimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
Here, you can create a custom MultipartRequest extends Request<JSONObject>
Hope this helps!
UPDATE FOR YOUR COMMENT:
I have a multipart entity is already included in apache http component libraries. Is there is any alternatives?
Here is my Request with HttpEntity and return a JSONArray. I think you can customize to return a JSONObject if you like.
private void makeJsonArrayRequest(Context context, int method, String url, HttpEntity httpEntity, final VolleyResponseListener listener) {
JSONObject jsonRequest = null;
String stringEntity;
try {
stringEntity = EntityUtils.toString(httpEntity);
if (stringEntity != null) {
jsonRequest = new JSONObject(stringEntity);
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
listener.onResponse(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(getErrorMessage(error));
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
...
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
...
}
};
// Access the RequestQueue through singleton class.
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}

Categories

Resources