Firebase send http cloud messaging from android app - android

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

Related

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

Sending POST Data in Android for Kairos API

I am looking to do as per the image says:
Following is the code I am trying to implement from that image:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://api.kairos.com/enroll";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.i("Response is: " , response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mTextView.setText("That didn't work!");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("app_id", "4985f625");
params.put("app_key", "aa9e5d2ec3b00306b2d9588c3a25d68e");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
Now I do not get how to add that JSONObject part into my POST Request, and also how to add the Content-Type Header.
I found a similar question here. See the code below. You have to override the getBodyContentType method.
public String getBodyContentType()
{
return "application/json";
}
for content type header you can do the following
StringRequest request = new StringRequest(Request.Method.PUT,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(#NonNull VolleyError error) {
if (error.networkResponse != null) {
errorListener.onErrorResponse(error.networkResponse.statusCode, null);
} else {
Log.e(TAG, "An error occurred while trying to verify sms: ", error);
errorListener.onErrorResponse(500, null);
}
}
}) {
#NonNull
#Override
protected Map<String, String> getParams() {
return data;
}
#NonNull
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type",
"application/x-www-form-urlencoded");
return headers;
}
};
And for send Json object I suggest create Json object like this
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
} catch (JSONException e) {
e.printStackTrace();
}
Then you can pass this object as string by jsonObject.toString() and pass it in parameters like pass any string like the following
#NonNull
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("json", jsonObject.toString();
return params;
}

WebAPI call using volley

I'm trying to get access tokens from the server using a volley String request. I have tried making a JsonObjectRequest also. Both are below.
public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.networkResponse.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("scope", "openid email phone profile offline_access roles");
params.put("resource", "window.location.origin");
params.put("grant_type", "password");
params.put("username", "support#xxx.com");
params.put("password", "tempPxxx");
return params;
}
};
requestQueue.add(request);
.
public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("scope", "openid email phone profile offline_access roles");
jsonParams.put("resource", "window.location.origin");
jsonParams.put("grant_type", "password");
jsonParams.put("username", "support#xxx.com");
jsonParams.put("password", "tempPxxx");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
if(null != response.toString())
listener.getResult(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.e(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
listener.getResult(null);
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// Map<String,String> params = super.getHeaders();
// if(params==null)params = new HashMap<>();
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
};
requestQueue.add(request);
.
I get the following response from the server:
E/Volley: [31388] BasicNetwork.performRequest: Unexpected response code 400 for https://lw.xxx.co.uk/connect/token
.
My colleague who has written the server-side code has asked how to convert the following Angular code (his code that works with the API), to Android.
Can anyone help with this?
getLoginEndpoint(userName: string, password: string): Observable<Response> {
let header = new Headers();
header.append("Content-Type", "application/x-www-form-urlencoded");
let searchParams = new URLSearchParams();
searchParams.append('username', userName);
searchParams.append('password', password);
searchParams.append('grant_type', 'password');
searchParams.append('scope', 'openid email phone profile offline_access roles');
searchParams.append('resource', window.location.origin);
let requestBody = searchParams.toString();
return this.http.post(this.loginUrl, requestBody, { headers: header });
}
The problem was a couple of things.
I replaced "params.put("resource", "window.location.origin"); " with "params.put("resource", "https://lw.xxx.co.uk");"
Also, I found out that Volley ignore the getHeaders override, so I commented that method out and used the following to set the headers.
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
public void getAuthenticationTokens(Object param1, final String userName, final String password, final CustomListener<JSONObject> listener)
{
String url = "https://lw.xxx.co.uk/connect/token";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.e("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.networkResponse.toString());
}
}
) {
/* #Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}*/
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("scope", "openid email phone profile offline_access roles");
params.put("resource", "https://lw.xxx.co.uk");
params.put("grant_type", "password");
params.put("username", userName);
params.put("password", password);
return params;
}
#Override
protected VolleyError parseNetworkError(VolleyError response) {
try {
String json = new String(response.networkResponse.data, HttpHeaderParser.parseCharset(response.networkResponse.headers));
Log.e(TAG, "reponse error = " + json);
}catch (Exception e){}
return super.parseNetworkError(response);
}
};
requestQueue.add(request);
}//end of getAuthenticationTokens

Not able to post params in form url-encoded through volley in android

I am trying hit an api(written in PHP) and posting params with it.
Here is my code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params.
I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?
Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems.
There is my code:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
String no = jsonObject.getString("$PhoneNo");
} catch (JSONException e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley " + error.toString());
}
})
{
#Override
public String getBodyContentType() {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
//return pars;
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
However I am still trying to figure out why JsonobjectRequest did not work.
As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."
And after searching again, I saw this thread.
if you are sending your data in raw format you need to try this,first of all make json of your data to be post.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
and you have to override these methods
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
if you also have header in your post request you also send that with by following type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
params.put("Authorization", auth_token);
return params;
}
Here is the whole code.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String token = jsonObject.getString("token");
prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);
if (status == 1) {
startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
} else if (status == 0) {
Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyApplication.getInstance().addToReqQueue(sr, "jreq");
}
} catch (Exception e) {
}
Try migrating to getHeaders and remove getParams
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return pars;
}
Or - Reuse the getParams method
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = getParams();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
If it is a body request all you need to do is add the extra parameter.
JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc#xyz.com");
body.put("pass", "a");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, body,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
});

Android Volley JsonObjectRequest not send params

I'm trying to send a JsonObjectRequest to my server with some params, but seems like params doesn't arrive at the server. Before to post on SO I try all kind of suggestion found in google but no one works fine..
This is the code of my JsonObjectRequest:
RequestQueue queue = MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
return params;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
And these are my param and others:
String url = "url";
//create the hashMap of parameters
database_zappapp db = new database_zappapp(getApplicationContext());
db.open();
HashMap<String, String> params = new HashMap<>();
params.put("action","myAction");
params.put("nomeutente", db.getUsernameLogged());
params.put("token", token);
db.close();
//Send the request to the server
Global.RequestJsonToServer(getApplicationContext(), url, Request.Method.POST, params);
Thanks in advance for the help!
Edit 2
I've changed my params in this creating a string jsonBody:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("action","gcmUserRegister");
jsonObject.put("nomeutente",db.getUsernameLogged());
jsonObject.put("token",token);
}catch(JSONException e){
e.printStackTrace();
}
String requestBody = jsonObject.toString();
db.close();
and my request like this with getBody():
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
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;
}
}
};
But already didn't work! =(
Postman screen:
No user found means that it enter in the if statement and so it works.. with android i receive "result": "null"
The postman screen with app/json:
I've found the solution!
The problem was in the server not in the client, I was getting the data using POST but from the client I was sending a json object so my new php is:
$data = json_decode(file_get_contents('php://input'), true);
//echo "Action: ".$action;
//Registrazione del token
if($data['action'] == "gcmUserRegister"){
......
Thanks al lot to BKS!!!
Change this part of your code:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null ...`
To this:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,yourparams..`
Reason: if you are using the default Volley constructors thats the way to send params to Server.

Categories

Resources