I am developing an application where Logging In returns a cookie named "authCookie" from server and this cookie is in header of the response. I am using Volley library and String Request for server-mobile application communication. Can you please guide me how do I get this cookie from header?
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if(obj.has("csrf") && obj.has("refreshToken")){
csrf = obj.getString("csrf");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null){
if(error.networkResponse.statusCode == 400){
Toast.makeText(MainActivity.this,"Invalid username/password",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(MainActivity.this,"Check internet connection!",Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
I want authCookie from response and save it in a string.
Related
So i have a get request from an API, when i get the response i want to make that response into a json file instead of making him an JSONOBJECT, is it possible ? i will paste the get funcion here, and the way im getting the JSONOBJECT.
I want to replace the way i get a JSONOBJECT, from a way to get that json as a file that goes to my assets directory.
public void getAssetPlant(final VolleyCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject j = new JSONObject(response);
callBack.onSuccess();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
requestQueue.add(request);
}
I'm finding the following error with my request post method: Unexpected response code 500 for POST method.
It was working fine and then it just stopped working and started to display this error.
this is my post method:
private void postRequest(String empresa, String matricula, String foto, String data, String face) {
RequestQueue requestQueue=Volley.newRequestQueue(MainActivity.this);
String url="http://can't show the url";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//anĂ¡lise de dados json
try {
JSONObject jsonObject = new JSONObject(response);
}
catch (Exception e){
e.printStackTrace();
// post_response_text.setText("POST DATA : unable to Parse Json");
}
Log.d("Response", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// post_response_text.setText("Post Data : Response Failed");
Log.d("Error.Response", error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params=new HashMap<String, String>();
params.put("Id", "");
params.put("Empresa", empresa);
params.put("Matricula", matricula);
params.put("Foto", foto);
params.put("Data", data);
params.put("GPS", finalLatitude + "|" + finalLongitude);
params.put("idDispositivo", getIMEI());
params.put("arquivo", "");
params.put("face", face);
params.put("ip", getIP());
return params;
}
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> params=new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
I tried to do the post request on postman and it's working fine.
How i'm sending information on postman: postman image
I am trying to convert Unirest
HttpResponse<String> response = Unirest.post("https://api.tap.company/v2/charges")
.header("authorization", "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ")
.header("content-type", "application/json")
.body("{\"amount\":1,\"currency\":\"KWD\",\"receipt\":{\"email\":false,\"sms\":true},\"customer\":{\"first_name\":\"test\",\"phone\":{\"country_code\":\"965\",\"number\":\"50000000\"}},\"source\":{\"id\":\"src_kw.knet\"},\"redirect\":{\"url\":\"http://your_website.com/redirect_url\"}}")
.asString();
to Volley
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.tap.company/v2/charges";
StringRequest TapREQUEST = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override public void onResponse(String response) {
Log.w("OnResponse:", response);
}
}, new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); }
}) {
#Override public Map<String, String> getHeaders() {
Map<String,String> headers = new HashMap<>();
headers.put("content-type", "application/json");
headers.put("authorization", "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ");
//String auth = "Bearer " + Base64.encodeToString("sk_test_XKokBfNWv6FIYuTMg5sLPjhJ".getBytes(), Base64.DEFAULT);
//headers.put("authorization", auth);
return headers;
}
#Override protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<>();
params.put("amount", String.valueOf(9.500));
params.put("currency","KWD");
params.put("receipt","{'email':false,'sms':true}");
params.put("customer",":{'first_name':'test','phone':{'country_code':'965','number':'50000000'}}");
params.put("source","{'id':'src_kw.knet'}");
params.put("redirect",":{'url':'http://ib7ar.com'}");
return params;
}
};
queue.add(TapREQUEST);
but I get
E/Volley: [396] BasicNetwork.performRequest: Unexpected response code 400 for https://api.tap.company/v2/charges
When I click on link I get
{"errors":[{"code":"2107","description":"Authorization Required"}]}
You have to set body parameters in different way. Let's create method returning correct string:
#NotNull
private JSONObject getJsonObject() {
JSONObject params = new JSONObject();
try {
params.put("amount", "1");
params.put("currency", "KWD");
JSONObject receipt = new JSONObject();
receipt.put("email", "false");
receipt.put("sms", "true");
params.put("receipt", receipt);
JSONObject customer = new JSONObject();
customer.put("first_name", "test");
JSONObject phone = new JSONObject();
phone.put("country_code", "965");
phone.put("number", "50000000");
customer.put("phone", phone);
params.put("customer", customer);
JSONObject id = new JSONObject();
id.put("id", "src_kw.knet");
params.put("source", id);
JSONObject url = new JSONObject();
url.put("url", "http://ib7ar.com");
params.put("redirect", url);
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
And now instead of getParams() you need getBody() method:
#Override
public byte[] getBody() {
try {
return getJsonObject().toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
The data appears as expected when I run the method in the debugger, however whenever I try to do anything with it the value of parentObject is returned as null.
I simply want to take the response from the server and store it as a JSONObject to be reused elsewhere.
public void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
/*
the data appears as expected within the debugger however
returns null when i attempt to use it elsewhere
*/
parentObject = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("phone", phone);
params.put("password", password);
return params;
}
};
mQueue.add(request);
}
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
parentObject = new JSONArray(obj);
for (int i = 0; i < parentObject.length(); i++) {
JSONObject parObj = (JSONObject) parArray.get(i);
ModelClass modelClass = new ModelClass()// you have to create a model
modelClass.set1Parameter(parObj.getString("1Parameter"));
modelClass.set2Parameter(parObj.getString("2Parameter"));
arrayList.add(modelClass)//In your arraylist save the data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
First of all you need to check what type response you getting from server i.e (JsonObject or JsonArray).
public void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
/*
if its JSONObject
*/
JSONObject jsonobject = new JSONObject(response);
String value= jsonobject.getString("value");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("phone", phone);
params.put("password", password);
return params;
}
};
mQueue.add(request);
}
as per your question ... you want to store response in jsonObject but in code you are store response in jsonArray
parentObject = new JSONArray(response);
so you must have to confirm response is in object or array.
if response is in object (like {}) change to parentObject = new JSONObject(response);
else change type of parentObject to JSONArray
I am new to using Volley on Android. Using the old http client stuff I could make my web requests perfectly with the various headers and parameters, now I am unable. My request looks like this in Postman:
POST /token HTTP/1.1
Host: my.api.co.za
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
username=test&password=1234&grant_type=password
Yet I am unable to recreate and execute this request in Volley. I have tried making a custom Json request class that extends Request<JSONObject> but to no avail. Please see my code below:
public class CustomJsonRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomJsonRequest(int method, String url, Listener<JSONObject> responseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = responseListener;
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", "test");
params.put("password", "1234");
params.put("grant_type", "password");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
/**
* Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
*/
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
encodedParams.deleteCharAt(encodedParams.lastIndexOf("&"));
Log.e("params", encodedParams.toString());
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.e("response", response.toString());
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
Log.e("response", response.toString());
listener.onResponse(response);
}
private Priority mPriority;
public void setPriority(Priority priority) {
mPriority = priority;
}
#Override
public Priority getPriority() {
return mPriority == null ? Priority.NORMAL : mPriority;
}
}
And I call this as follows in my MainActivity class:
CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, AUTH_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//showJSON(response);
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtError(error);
}
});
Can somebody tell me where I am going wrong in creating this request?
You can try with my following sample code:
String url = "http://server/token";
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "bnk");
stringMap.put("password", "bnk123");
Uri.Builder builder = new Uri.Builder();
Iterator entries = stringMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove();
}
String requestBody = builder.build().getEncodedQuery();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
};
UPDATE:
If your project uses Google's official volley as a module, you should add the following into JsonObjectRequest.java file:
public JsonObjectRequest(int method, String url, String requestBody,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
UPDATE 2:
If you don't want to edit JsonObjectRequest.java file as I mentioned above, you can use the following code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() {
// init parameters
Map<String, String> params = new HashMap<>();
params.put("grant_type", "password");
params.put("username", "bnk");
params.put("password", "bnk123");
// encode parameters (can use Uri.Builder as above)
String paramsEncoding = "UTF-8";
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
};
Hope it helps!