问题描述
我对Android来说还比较陌生,我正在探索新的功能和API,并且我已经开发了一个简单的聊天应用程序,安静了几个星期,以了解更多关于android的知识。因此,我一直在尝试在我的应用中实现通知,实际上我提出了一些安静的解决方案。我尝试使用AlarmManagers,但实际上效果不佳,因此我求助于FCM,实际上我设法通过FCM控制台推送通知,但是当我尝试使用Retrofit2发送带有序列化正文和标题的发帖请求时,我从服务器返回了400错误响应代码。我还尝试使用在GitHub上找到的其他代码,它们都给了我相同的响应代码。
ApiInterface类:
public interface APIInterface {
@Headers({"Authorization: key=AAAAcbbYIW4:APA91bHefWZnNKFoFhYRjDMVDMMp41-3zjt6RWcr_tku7NmvbedDHDmZZCpfwc51rU-VlFsCMy_5dTp3YEN_3dvoDUPp1YRte7z1_iosdJwzS97VZ4wYjivgUT9VCe1f9_OGv","Content-Type:application/json"})
@POST("fcm/send")
Call<ResponseBody> sendNotification(@Body NotificationBody body);
}
通知正文类别:
public class NotificationBody {
@Serializedname("token")
private String token;
@Serializedname("notification")
private NotificationContent notificationContent;
public void setToken(String token) {
this.token = token;
}
public void setNotificationContent(NotificationContent notificationContent) {
this.notificationContent = notificationContent;
}
}
public class NotificationContent {
@Serializedname("title")
String title;
@Serializedname("body")
String body;
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
}
改装客户端:
public class RetrofitClient {
public static final String BASE_URL = "https://fcm.googleapis.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Firebase令牌类:
public class FirebaseInstanceIDService extends FirebaseMessagingService {
String token;
@Override
public void onNewToken(@NonNull String s) {
super.onNewToken(s);
token = s;
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser!=null){
updatetoken(s);
}
}
public void updatetoken(String mToken){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("TOKENS");
assert firebaseUser != null;
reference.child(firebaseUser.getUid()).setValue(mToken);
}
}
我不确定生成的Token或我的请求正文是否有问题,无论如何我都会得到400个代码。有人可以帮我吗?。在此先感谢:)
解决方法
由于要作为有效负载发送的JSON结构错误,因此您收到400 HTTP错误。正确的结构在下面。
{
"to": "<receiver_device_token_here>","notification": {
"title": "title for the notification"
"body": "body for the notification"
}
}
那么,您的代码有什么错误?你用过
"token": "<receiver_device_token_here>"
代替
"to": "<receiver_device_token_here>"
只需更改您的NotificationBody
POJO类,如下所示
public class NotificationBody {
@SerializedName("to") // <<======= CHANGE THE NAME FROM token TO to
private String token;
@SerializedName("notification")
private NotificationContent notificationContent;
public void setToken(String token) {
this.token = token;
}
public void setNotificationContent(NotificationContent notificationContent) {
this.notificationContent = notificationContent;
}
}