Java使用UTF-8发送http POST

问题描述 投票:2回答:2

我需要使用Google FCM发送HTTP POST。使用下面的代码,可以发送英文信息但中文字符。我在这里和那里添加了UTF-8做了很多试验...需要帮助。

我的消息的有效负载在下面的代码中是str2。 Android APP中显示的结果是Hello +%E6%88%91

E68891是正确的UTF-8代码,但我需要将其显示为中文字符。

package tryHttpPost2;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;

public class TryHttpPost2 
{
    public static void main(String[] args) throws Exception {
        String url = "https://fcm.googleapis.com/fcm/send";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json;x-www-form-urlencoded;charset=UTF-8");
        con.setRequestProperty("Accept-Charset", "UTF-8");
        con.setRequestProperty("Authorization", "key=...............");

        String str1 = "{\"to\":\"/topics/1\",\"notification\":{\"title\":\"";
        String str2 = URLEncoder.encode("Hello 我", "utf-8");
        String str3 = "\"}}";
        String urlParameters = str1+str2+str3;
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        con.getResponseCode();
    }
}
java http post firebase-cloud-messaging
2个回答
3
投票

有两个问题:

  1. writeBytes:正如Java文档所说: 对于每个字符,写入一个字节,即低位字节,与writeByte方法完全相同。字符串中每个字符的高位8位被忽略。 所以这个方法不能写unicode字符串。
  2. URLEncoder旨在用于GETrequests或POST请求,内容类型为application/x-www-form-urlencoded。但是您使用内容类型application/json传输数据。你不知何故尝试在那里使用url编码,但这不起作用。 (有关更多信息,请参阅relevant RFC

要解决此问题,请使用正确的方法传输数据:as utf-8,在JSON中没有任何编码:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Authorization", "key=...............");

String str1 = "{\"to\":\"/topics/1\",\"notification\":\"title\":\"";
String str2 = "Hello 我";
String str3 = "\"}}";
String urlParameters = str1+str2+str3;
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8");

wr.write(urlParameters);
wr.flush();
wr.close();
con.getResponseCode();

1
投票

感谢Kuhn的大力帮助。这就是我现在所做的工作。

  1. 让Content-Type只是“application / json”。
  2. 让str2只是有效​​负载字符串。
  3. 用wr.write替换writeBytes事物(urlParameters.getBytes(“utf-8”)); “Accept-Charset”这个属性在这里似乎毫无用处。无论是否有效。
© www.soinside.com 2019 - 2024. All rights reserved.