Java如何给极光推送发消息
一,项目背景,我是负责App端开发的,不过由于公司小人手不足,因此也要写一些后台的小程序,国内的推送平台还是比较多的,有极光、个推、信鸽等等,下面聊一下服务端如何来给极光的服务端推送消息,以达到让极光服务端正常接收并推送消息到我们自己的App的开发流程。
二、文档参考,http://docs.jiguang.cn/,这里有App端、服务端的开发文档,本文只涉及服务端的开发。服务端的文档参考http://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/。开发之前我先用Postman测通了http的请求,如下图。
认证方式HTTP Basic Authentication,如果不清楚的可以参考极光文档或者搜索引擎。填上认证的用户名和密码,接下来是请求的body。如下图,
body为一个json字符串,我这里只推送给iOS的,没有给推给Android,需要的话加上即可。extra并非必须字段。其他字段的相关意义,这里也不赘述。然后点击send,发送成功的话返回的数据如下:
测试没有问题,下面直接上程序,
这里是推送的主体
- {
- "platform": "all",
- "audience": {
- "alias":["这里填上注册设备的别名,当然也可以通过tag或者registerId发送"]},
- "notification": {
- "android": {
- "alert": "我是消息内容",
- "title": "peter",
- "builder_id": "1",
- "extras": {//自定义字段,可不要
- "senderId": "peter",
- "pushUrl":"http://www.baidu.com"
- }
- },
- "ios": {
- "alert": "我是消息内容",
- "title": "peter",
- "sound": "default",
- "badge": "0",
- "extras": {
- "senderId": "peter",
- "pushUrl":"http://www.baidu.com"
- }
- }
- },
- "options": {
- "time_to_live": 60,
- "apns_production": true
- }
- }
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- public class TestJpush {
- private static String JPUSH_URL = "https://api.jpush.cn/v3/push";
- private static String JPUSH_AUTH = "这里填上你的验证信息,格式大致为Basic xxxxxxxxxxxxxxxxxxxxxxxxxxx";
- public static void main (String args[]) {
- TestJpush test = new TestJpush();
- test.sendHttpsRequest("Json串");//这里替换为上面的json
- }
- public void sendHttpsRequest(String param) {
- if (param == null) {
- return;
- }
- long responseLength = 0;
- String responseContent = null;
- HttpClient httpClient = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(JPUSH_URL);
- try{
- httpPost.setHeader("Authorization", JPUSH_AUTH);
- httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
- HttpEntity requestEntity = new StringEntity(param, "UTF-8");
- httpPost.setEntity(requestEntity);
- HttpResponse response = httpClient.execute(httpPost);
- HttpEntity entry = response.getEntity();
- if (entry != null) {
- responseLength = entry.getContentLength();
- responseContent = EntityUtils.toString(entry, "UTF-8");
- EntityUtils.consume(entry);
- }
- } catch(ClientProtocolException e) {
- e.printStackTrace();
- } catch(UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch(IOException e) {
- e.printStackTrace();
- } finally {
- httpClient.getConnectionManager().shutdown();
- }
- System.out.println("content="+responseContent);
- //推送成功返回字段 {"sendno":"0","msg_id":"4161322531"}
- }
- }
编译,运行,如果成功的话,控制台会输出如下数据。