How to put Cookie session id into volley request? - android

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

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

Custom Gson request and response in post method

What have I done wrong?. How can i resolve this?. Please explain why this error occur. if it is run successfully what is my response?
MainActivity :
public class MainActivity extends AppCompatActivity {
String url = "http://vsstechnology.com/DTSignUp/api/business/create_business.php";
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
HashMap<String, String> params = new HashMap<>();
params.put("address", "xxx");
params.put("business_description", "xx");
params.put("businessEmail", "xxx#gmail.com");
params.put("business_name", "xxx");
params.put("phone", "1234567890");
params.put("business_type", "xx");
params.put("created_by", "xxx");
params.put("customer_name", "xxx");
params.put("email", "yyy#gmail.com");
params.put("firstName", "yyy");
params.put("lastName", "yyy");
params.put("phone", "6544324569");
GsonRequest<Model> gsonRequest = new GsonRequest<Model>(Request.Method.POST, url, Model.class, params, new Response.Listener<Model>() {
#Override
public void onResponse(Model response) {
Toast.makeText(getApplicationContext(), "success" + " " + response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error" + " " + error, Toast.LENGTH_LONG).show();
}
});
requestQueue.add(gsonRequest);
}
}
Model :
public class Model {
private Business business;
private Contacts[] contacts;
private ServerResponse serverResponse;
public Model(Business business, Contacts[] contacts, ServerResponse serverResponse) {
this.business = business;
this.contacts = contacts;
this.serverResponse = serverResponse;
}
public Business getBusiness() {
return business;
}
public void setBusiness(Business business) {
this.business = business;
}
public Contacts[] getContacts() {
return contacts;
}
public void setContacts(Contacts[] contacts) {
this.contacts = contacts;
}
public ServerResponse getServerResponse() {
return serverResponse;
}
public void setServerResponse(ServerResponse serverResponse) {
this.serverResponse = serverResponse;
}
}
custom GsonRequest :
public class GsonRequest<T> extends Request<T> {
private Gson gson = new Gson();
private Class<T> clazz;
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param params Map of request headers
*/
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> params,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.headers = null;
this.params = params;
this.listener = listener;
gson = new Gson();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
Error :
com.android.volley.ParseError : com.Google.gson.JsonSyntaxException:
java.lang.illegalStateException: Expected BEGIN_OBJECT but was STRING
at line 1 column 1 path $
Based on your error some thing is wrong with your API, to debug it you can use Postman.

Send Object as Data with POST Method in Android Volley?

I am using POST method and trying to Send Object as data using Android Volley Library to change the Current Password to New One but I am not Able to do it.
SettingFragment
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
/*
// JSONObject js = new JSONObject();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
// error.getMessage();
}
}) {
#Override
public String getBodyContentType() {
return "Content-Type;application/x-www-form-urlencoded";
}
#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
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
*/
// JSONObject params = new JSONObject();
// params.put(KEY_Name, Name);
// params.put(KEY_MasterID, master_id);
// params.put(KEY_USERNAME, username);
// params.put(KEY_OldPASSWORD, oldpassword);
// params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
// headers.put(KEY_Name, Name);
// headers.put(KEY_MasterID, master_id);
// headers.put(KEY_USERNAME, username);
// headers.put(KEY_OldPASSWORD, oldpassword);
// headers.put(KEY_UserPassword, newpassword);
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Backend object looks like
Users = {
NAME: vm.name,
UserName: vm.currentUserName,
oldPassword:vm.oldPassword,
UserPassword: vm.UserPassword
Users.MasterID = vm.masterID;
}
I am able to send through the POSTMan but through Code i am not able to do it.
logcat
05-29 16:16:49.764 1114-2077/com.example.user.mis E/Volley: [651] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.100.5:84/api/usersApi/updateByMasterID
How can this issue be Solved?
You may try this code, I have implemented the same thing as you do ... it might work for you
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put(KEY_Name, Name);
headers.put(KEY_MasterID, master_id);
headers.put(KEY_USERNAME, username);
headers.put(KEY_OldPASSWORD, oldpassword);
headers.put(KEY_UserPassword, newpassword);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
You can try this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#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
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
You should change the StringRequest to JSONObjectRequest as you are working with a JSON object in the backend. So you should pass the strings as a JSON object and then it might work.
private void makeJsonObjectRequest() throws JSONException {
JSONObject cred = new JSONObject();
cred.put("username", username.getText().toString());
cred.put("password", password.getText().toString());
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(Request.Method.POST,
urlJsonPost, cred, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
//aftererror:
try {
// Parsing json object response
// response will be a json object
token = response.getString("token");
adminName = response.getString("adminName");
jsonResponse = "";
jsonResponse += "token:" + token ;
jsonResponse += "adminName:" + adminName;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"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(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}});AppController.getInstance().addToRequestQueue(jsonObjReq);
You would also need to create a class named AppController.java and punch in the below code
import android.app.Application;
import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
You can also send POST parameters as JSONObject with the StringRequest.
Try this one:
private static final String KEY_Name = "NAME"
private static final String KEY_MasterID = "MasterID"
private static final String KEY_USERNAME = "UserName"
private static final String KEY_OldPASSWORD = "oldPassword"
private static final String KEY_UserPassword= "UserPassword"
..........
..................
JSONObject params = new JSONObject();
params.put(KEY_Name, Name);
params.put(KEY_MasterID, master_id);
params.put(KEY_USERNAME, username);
params.put(KEY_OldPASSWORD, oldpassword);
params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Navigation_URL_SettingRequest, params,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
..............
...................
I have broken masterID and Send only the integer for the login, but in the changing password i want all the masterID without broken.Which is not added by me,thats the error and has to sent through the parameter section.
working code is shown below
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, "s" + master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}

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

How to send the string which is part of URL from volley?

It may be dumb question but i struck with this am making simple login application using volley need to post String which is part of URL like this http://xxx.xx.x./{user_id}/{passwrd} and need to get json response from server so far what i have tried is :
private void registerUser(final String s, final String s1){
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("email", s);
jsonParams.put("username", s1);
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String yog=response.toString();
Log.e("Yog",yog);
mProgressView.setVisibility(View.INVISIBLE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,s);
params.put(KEY_PASSWORD,s1);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
and calling this method inside onclick listener don't know where am making mistake can anybody help me ?
Try this
private void postDatalogin(String Usermail, String Userpwd,
String Devicetype, String Deviceid, String osname, String version, String ip) {
/* XMl Http Post */
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = null;
List<NameValuePair> nameValuePair = null;
httpPost = new HttpPost(
Loginurl);
// Building post parameters
// key and value pair
nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", Usermail));
//nameValuePair.add(new BasicNameValuePair("device_information",Deviceinfo));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
String strRet = HttpHelper.request(response);
Log.d(strRet, "strstrRet");
try {
JSONObject jsonObjRecv = new JSONObject(strRet);
String result = jsonObjRecv.getString("status");
Log.d(result, "result");
String message = jsonObjRecv.getString("info");
Log.d(message, "message");
String userid = "", username = "", useremail;
if (result.equals("Success")) {
userid = jsonObjRecv.getString("userid");
useremail = jsonObjRecv.getString("email");
username = jsonObjRecv.getString("username");
Log.d(userid, "userid");
SharedPreferences app_preferences1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = app_preferences1.edit();
editor.putBoolean("login", true);
editor.putString("userid", userid);
editor.putString("usermaiid", useremail);
editor.commit();
hidepDialog();
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} else {
hidepDialog();
showalert(message);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
just append your password in the URL http://xxx.xx.x./myId/mypass the params can be null or no value
private ProgressDialog pDialog;
private String tag_json_obj = "jobj_req";
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
String Url="http://x/x/x/x/Login?user_email=er.naveen,tamrakar#gmail.com&password=123123123";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
Url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
mResponseTextView.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* 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");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

Categories

Resources