我正在尝试使用 Firebase 云消息发送带有特殊字符(例如俄语字符)的消息。相关代码在这里:
来自应用发件人:
String message = tv.getText().toString(); //get text from UI text view
....
App myapp = new App.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(getString(R.string.app_name)).build();
try {
//send the message to the server
myapp.sendToGroup(new String(message.getBytes(StandardCharsets.UTF_8),
StandardCharsets.UTF_8)).execute();
} catch (IOException e) {
return;
}
来自服务器:
Map<String, JsonElement> dataMap = new HashMap<>();
dataMap.put(MSG, new JsonPrimitive(message));
pushMessage.setData(dataMap);
HttpURLConnection conn = null;
URL url = new URL("https://fcm.googleapis.com/fcm/send");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("project_id", "xxxxxxx");
conn.setRequestProperty("Authorization", "key=" + FCM_API_KEY);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
.......//send the request here
应用接收服务:
public class CloudListenerService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String message = data.get(MSG);
if (message == null)
return;
Bundle b = new Bundle();
Intent r = getNewIntent();
b.putString(Receiver.EXTRA_MESSAGE, new String(message.getBytes(StandardCharsets.UTF_8),
StandardCharsets.UTF_8));
sendBroadcast(r);
}
}
我看到的消息是??????这只是意味着编码有问题。从服务器我可以看到用 %23clip%23%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80 编码的正确字符串(即#clip#пример 我发送的文本) .哪里出错了?
最佳答案
发现的问题:我以错误的方式创建了 writer。我更改了代码从
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
到
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
关于android - 带有特殊字符的 Firebase 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352163/