需要推送的body为:
{
"to":"cp9rjOYxFZ8:APA91bF0Ao5mq_9XsYMtu2DPov2yIH9minFrPEMLFm4OQA3Yk6mkgEXA5opqHo9I15-q7cwzF_iuQu7nja7pDvivDN4KBXznUZPnWYSqwy3qJFWt7r94JXQ4WcOYy7rC1G7z1PzjZ611",
"data":{
"notificationType":"11",
"userName":"Henry",
"baseName":"cute animals",
"baseCode":"ciika",
"userId":"cikka"
}
}
URLConnection代码为:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class PostJson {
public static void send(String urlPath, String content) {
try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "key=AIzaSyCYFxP9cRIt1Z3BRVE55022QcQH2ledcde");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println(sb);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String body = "见上面示例";
send("https://fcm.googleapis.com/fcm/send", body);
}
}
返回为:
{
"multicast_id": 4746322810404192896,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1506080066562889%a9dfa1c2f9fd7ecd"
}
]
}