我想使用firebase云消息发送推送通知。 我已成功以共享首选项存储访问令牌。
我正在使用Volley向服务器发送请求,但发送请求后它(Volley)显示 com.android.volley.Server错误。
注意:我只是在同一设备上发送firebase推送通知,因为请求主体中传递的访问令牌是相同的(当前)用户
@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);
}
答案 0 :(得分:2)
进行简单的POST操作似乎有点过分。我认为使用OkHTTP之类的东西来执行此操作会更好。它应该是一个非常简单的POST操作
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();
}
答案 1 :(得分:0)
我认为以下代码存在问题: -
@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;
}