带有特殊字符的Firebase消息

问题描述 投票:0回答:1

我正在尝试使用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#пример)编码的正确字符串。错误在哪里?

android character-encoding firebase-cloud-messaging urlencode
1个回答
0
投票

发现问题:我以错误的方式创建了作家。我从[>]更改了代码

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

to

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
© www.soinside.com 2019 - 2024. All rights reserved.