Sending firebase push notification using volley - android

I want to send push notification using firebase cloud messaging.
I have successfully stored access token in shared preference.
I am using Volley to send request to server but it(Volley) shows com.android.volley.Server error after sending the request.
Note: I am just sending firebase push notification on same device since the access token passed in body of request is of same(current) user
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String token= Helper.getAccessToken(this);
if(token!=null){
sendRequest();
}
}
private void sendRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url= "https://fcm.googleapis.com/fcm/send";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();//Here ServerError shows
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
String accessToken = Helper.getAccessToken(MainActivity.this);
params.put("to",accessToken);
params.put("title", "This is string message");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> header = new HashMap<>();
header.put(""Authorization,"key=" + "Here is my server key");
header.put("Content-Type","application/json");
return header;
}
}
;
requestQueue.add(request);
}

It seems a little bit overkill just to make a simple POST operation. I think it would be better to use something like OkHTTP to carry out this operation. It should be a very straightforward POST operation
private void sendRequestByOk() {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject jsonData = new JSONObject();
try {
jsonData.put("body","Hi!! This is the message from device");
jsonData.put("title","dummy title");
json.put("notification",jsonData);
json.put("to",Helper.getAccessToken(MainActivity.this));
RequestBody body = RequestBody.create(JSON,json.toString());
okhttp3.Request request = new okhttp3.Request.Builder()
.header(AUTHORIZATION_KEY,AUTH_VALUE)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
okhttp3.Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
// Toast.makeText(MainActivity.this, finalResponse,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
}.execute();
}

I think there is problem in below code:-
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
String accessToken = Helper.getAccessToken(MainActivity.this);
params.put("to",accessToken);
//change this
params.put("notification", "This is string message");
return params;
}

Related

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.

sending username and password via post request in volley in android

I am using this url to send post reqeust via volley:"http://136.243.146.41:8443/api/GetMainCategories".
here is my code:
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, mainmenurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject("{response}");
//makemainmenulist();
Toast.makeText(Cofeelist.this,"success!--->>>>"+response, Toast.LENGTH_LONG).show();
Log.i("sucsses!.....",response);
// value1= jsonResponse.getString("Your ID1");
// value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Cofeelist.this,"error1!--->>>>"+e, Toast.LENGTH_LONG).show();
Log.i("Error1!.....",e+"");
// banner_id = null;
// full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(Cofeelist.this,"error2!--->>>>"+error, Toast.LENGTH_LONG).show();
Log.i("error2!.....",error+"");
// value1= null;
// value2= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", "pourya");
params.put("key", "54a65sdf4a35s4d");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
but i got this error:"com.android.volley.NoConnectionError: java.io.EOFException ".i changed the url to"tarkhinehapp/api/GetMainCategories" but i got another error " com.android.volley.ServerError"
Have you checked the server log?
I used volley lib to connect to server and sent username and pass via querystring in url as below:
MyVolleyStringRequest mainmenureq=new MyVolleyStringRequest(Request.Method.GET, G.urlBase+"MainCategoriesApi?username="+"username"+"&"+"key="+"pass",new MyListener(this));
the volley made my job so easy!

Missing parameters Kairos API with Android Volley POST

I'm trying to use KairosAPI's enroll POST request using Android Volley. However I keep getting Error 1002, image one or more required parameters are missing. I've tried two ways to add the parameters into the body of the JSON, which I've outlined in the code.
This is my code-
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequestToEnrollPersonInGallery();
}
public void postRequestToEnrollPersonInGallery() {
final String appId = "3e12****";
final String appKey = "156e06fd782a3304f085f***********";
String mainUrl = "https://api.kairos.com/";
String enrollRequestUrl = "enroll";
requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, mainUrl + enrollRequestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("app_id", appId);
params.put("app_key", appKey);
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
/*params.put("image", "\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg\"");
params.put("subject_id", "\"subject_id\":\"12345\"");
params.put("gallery_name", "\"gallery_name\":\"FirstGallery\""); -- i tried this too*/
return params;
}
};
requestQueue.add(stringRequest);
}
}
You aren't posting JSON.
You can either
1) Learn to use JsonObjectRequest
final JSONObject body = new JSONObject();
body.put(... , ...);
Request request = new JsonObjectRequest(url, body, ...);
2) Actually post a JSON String.
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject params = new JSONObject();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
return params.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};

Android Volley POST Parameters

I need to call an api that expects a string array as a POST parameter. So for an example of an API definition:
POST api/names
POST parameter expected is an array of names and some other attributes like below:
{ names: [ "John", "Bill" ], department: "Engineering" }
I am currently using a custom Volley framework as described in the Android documentation but it seems like the parameters from Volley can only be passed as a Map of (String, String as key and value). I already have the array from my Android app, ready to be passed as a post parameter but this Volley expects a String.
I tried to convert my array using Arrays.toString(myStringArray) and passed it like below but it does not work.
String[] namesArray = new String[1];
namesArray[0] = "Bill";
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("department", "Computer Science");
mapParams.put("names", Arrays.toString(namesArray));
// Then call the Volley here passing the mapParams.
How can I call the api that expects a String of array when I can only use a String from Volley?
I will give you full code to post JsonObject on volley, through POST method.
JSONObject js = new JSONObject();
try {
js.put("genderType", "MALE");
}
} catch (JSONException e) {
e.printStackTrace();
}
String url = "LINK TO POST/";
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Response_Code from Volley" + "\n" + response.toString() + " i am king");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e(TAG, "Error: " + error.getMessage());
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
Log.e(TAG, "onErrorResponse: of uploadUser" + res);
// JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
}
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Log.e(TAG, "uploadUser: near volley new request ");
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
}
Put anything you need in the js object with key and its values
Use JsonObjectRequest and simply pass a JSONObject. There's a full example here
public void makePostRequest(final Map<String,String> myMap,String MEDIA_URL,final VolleyResponse callback)
{
VolleySingleton VS;
Log.e("URL",MEDIA_URL);
VS=VS.getInstance();
RequestQueue rq=VS.getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.POST,MEDIA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
callback.onSuccess(s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
callback.onError();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new Hashtable<String, String>();
Iterator<Map.Entry<String, String>> iterator = myMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String,String> pairs = (Map.Entry<String,String>)iterator.next();
String value = pairs.getValue();
String key = pairs.getKey();
params.put(key,value);
Log.e("Key","Value"+value);
}
return params;
}
};
//Creating a Request Queue
// RequestQueue requestQueue = Volley.newRequestQueue(this);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
//Adding request to the queue
rq.add(stringRequest);
}
Where the VolleyResponse is a simple custom interface like this
public interface VolleyResponse {
void onSuccess(String resp);
void onError();
}

How to send a POST request using volley with string body?

I'm developing an Android app that communicate with a RESTful web service I wrote. Using Volley for GET methods is awesome and easy, but I can't put my finger on the POST methods.
I want to send a POST request with a String in the body of the request, and retrieve the raw response of the web service (like 200 ok, 500 server error).
All I could find is the StringRequest which doesn't allow to send with data (body), and also it bounds me to receive a parsed String response.
I also came across JsonObjectRequest which accepts data (body) but retrieve a parsed JSONObject response.
I decided to write my own implementation, but I cannot find a way to receive the raw response from the web service. How can I do it?
You can refer to the following code (of course you can customize to get more details of the network response):
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
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();
}
I liked this one, but it is sending JSON not string as requested in the question, reposting the code here, in case the original github got removed or changed, and this one found to be useful by someone.
public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user",userAccount.getUsername());
params.put("pass",userAccount.getPassword());
params.put("comment", Uri.encode(comment));
params.put("comment_post_ID",String.valueOf(postId));
params.put("blogId",String.valueOf(blogId));
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(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();
JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();
StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Rest response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest response",error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("name","xyz");
return params;
}
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("content-type","application/fesf");
return params;
}
};
requestQueue.add(stringRequest);
I created a function for a Volley Request. You just need to pass the arguments :
public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("username", username);
MyData.put("password", password);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}

Categories

Resources