Send token in header using volley library in android - android

I'm trying to send Get request to server using volley library in android but it failed to get response but when I send the same request from Postman it success to get response. I must to send token parameter in header to get the response. what is the problem although I add token in the request in java code but it failed to get response ?
Android Java code
public static void sendPostRequest(Context context, String token, HashMap<String, String> parameters)
{
try {
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://api.palcharge.com/WS/listProviders?username=api",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
// handle response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toasty.warning(SelectBlog.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> params = new HashMap<>();
params.put("token", token);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
Log.d("Request", stringRequest.getHeaders().toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
Snapshot from Postman when I send request

#Override
public Map<String, String> getHeaders() {
HashMap<String, String> params = new HashMap<>();
params.put("Authorization", "Bearer " + token);
return params;
}

Related

getHeaders Override method not being added to request

I'm trying to do a simple GET request in Android via Volley. However when I debug it the override method(s) are only called AFTER the request has been added to the queue. So my request thinks the headers object is empty and fails on the backend check. How can I make the request consume my headers before being sent to the backend?? I've looked at examples everywhere and I can't figure out why mine doesn't work. Please help!
private void getHello(){
String helloUrl = "https://...";
final String basicAuth = "Basic " + Base64.encodeToString("testUser:somePassword".getBytes(), Base64.NO_WRAP);
StringRequest stringRequest = new StringRequest(Request.Method.GET, helloUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Hello Response: ",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Hello Response Error: ",error.toString());
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("X-FXF-clientid", "123");
params.put("authorization", basicAuth);
return params;
}
};
queue.add(stringRequest);
}

How to print the request of my multipart volley request in log

This is my volley multipart request. But request parameters are received empty in the backend. I am not sure where the error is in front-end or backend. So for ensuring I want to print the request, I am sending in the Log.
String url = Globals.BASE_URL +Globals.PAN_UPLOAD;
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
progressBar.setVisibility(View.GONE);
changeUiUpload();
try {
JSONObject jsonObject = new JSONObject(response);
Utils.createSnackBarWithAction(activity,jsonObject.getString("ResponseMessage"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Utils.createSnackBarWithAction(activity,error.toString());
}
}){
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + Utils.decrypt(session.getOauthToken()));
return params;
}
};
smr.addStringParam("auth_token",session.getAuthToken());
smr.addStringParam("document_password", "");
smr.addStringParam("document_type","1");
smr.addStringParam("document_subtype","1");
smr.addStringParam("user_type", "b");
smr.addStringParam("skip_kyd","no");
smr.addStringParam("check_password","1");
smr.addStringParam("total_files", "1");
smr.addStringParam("file_name_prefix","file_upload");
smr.addStringParam("is_pwd_array","no");
smr.addStringParam("pwd_list_name", "document_password");
smr.addStringParam("is_single_file","1");
smr.addFile("file_upload",file.getAbsolutePath());
/*Log.i("PanUploadRequest","Auth Token : "+session.getAuthToken()+" File Path : "+
file.getAbsolutePath()+" Borrower Id : "+session.getBorrowerId());*/
Log.i("PanUploadRequest", String.valueOf(smr.getMultipartParams()));
RequestQueue mRequestQueue = Volley.newRequestQueue(AppController.getContext());
mRequestQueue.add(smr);
You can just write this code before your adding the request to the queue:
VolleyLog.DEBUG = true;
Don't forget to remove this line after you are done debugging.

Firebase send http cloud messaging from android app

I am currently sending firebase cloud messages from Postman, using an http post request. Its all working fine. I am now trying to make a simple Android app to send the messages from, . However it doesn't work and I get either InvalidRegistration or MissingRegistration or com.android.volley.AuthFailureError
In postman, I do an http post request to https://fcm.googleapis.com/fcm/send
With 2 headers:
Key: 'Authorization' Value: 'key=AAAAnfdQ2jM:AP....'
Key: 'Content-Type' Value: application/json
Then in body, using raw:
{
"to": "/topics/anytopic",
"data": {
"my_message": "Hi everyone!",
}
}
Where and how do I put this information in my volley http post request?
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST,"https://fcm.googleapis.com/fcm/send", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
I can't find any example of this.
Thanks so much.
You need to add a JSON body like this:
JSONObject jsonBody = new JSONObject();
jsonBody.put("to", REUVEN_TOKEN_BE_YOUNG);
JSONObject jsonObject = new JSONObject();
jsonObject.put("my_message", "Keep eating healthy!");
jsonBody.putOpt("data", jsonObject);
final String requestBody = jsonBody.toString();
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST,"https://fcm.googleapis.com/fcm/send", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "That didn't work..." + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Authorization",BE_YOUNG_APP_KEY);
return params;
}
#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;
}
}
};
queue.add(sr);

Json data not displaying in real device, but works well on Emulator [duplicate]

I am trying to connect to a django server from my android application. I am trying to access my api, making a POST request with volly. Everything is set. All the params and headers required, but still I get this error.
log: [490] BasicNetwork.performRequest: Unexpected response code 401 for https://example.com/
It's not letting me access my django Api. It works fine with the PHP server.
public void vollyRequest()
{
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST , "https://example.com/", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, "RESPONSE: " + response, Toast.LENGTH_SHORT ).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "ERROR: " + error, Toast.LENGTH_SHORT ).show();
}
}) {
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","***");
params.put("password","***");
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;
// }
};
queue.add(request);
}
i solved it my self...
This code will get you an auth-token, with the username and password you provide, and then that token will be put in the header to get data from the server...
public void vollyRequestGetAuthToken()
{
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST , "https://example.com/get-auth-token/", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, "RESPONSE: " + response, Toast.LENGTH_SHORT ).show();
System.out.println("RESPONSE: >>> " + response + "<<<");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "ERROR: " + error, Toast.LENGTH_SHORT ).show();
}
}) {
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","*****");
params.put("password","*****");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Authorization",
String.format("Basic %s", Base64.encodeToString(
String.format("%s:%s", "<username>", "<password>").getBytes(), Base64.DEFAULT)));
params.put("username" , "*****" );
params.put("password" , "*****" );
return params;
}
};
queue.add(request);
}
and now when you have the auth-token, use the following code to send auth-token to get data
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token <token>");
return headers;
}
This is caused when the request is declined/blocked from the API End Point.
The reason could be a malformed request for that,
Check your request type [GET/POST/ANY OTHER]
Check the request Header and Body

Passing Parameters into Android Volley POST Request, return JSON

I am attempting a Volley POST request that passes in the parameter friends_phone_number_csv that should then return a JSON object. However in using the request below it simply notes:
E/Volley﹕ [4230] BasicNetwork.performRequest: Unexpected response code 500 for http://(ip-address):3000/getActivatedFriends.json
In testing this request in chromes POSTMAN I know the webservice is correct and should return a JSON object.
How can I make this work?
The POST request in app:
JsonObjectRequest getUserActiveFriends = new JsonObjectRequest(Request.Method.POST, "http://" + Global.getFeastOnline() + "/getActivatedFriends.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("friends_match");
Toast.makeText(getApplicationContext(), resultObject.toString(), Toast.LENGTH_LONG).show();
// PARSE THE REST
//Log.v("USER ID", "The user id is " + userId);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("friends_phone_number_csv", contactsNumbers);
return params;
}
};
requestQueue.add(getUserActiveFriends);
You should add this code, when you post request and return json data, you should add content type "application/json; charset=utf-8" to http header.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}

Categories

Resources