alertover推送api的java httpclient实现实例

来源:互联网 发布:翻译软件哪个好 编辑:程序博客网 时间:2024/06/09 10:28

本人前几天发现一款很好用的推送app——alertover,但是官网api的应用示例竟然没有java应用的示例,所以自己尝试写了一个。使用httpclient请求了一下post接口,传了一下json数据,判断一下响应的状态码。现分享代码,共大家参考。

public static void sendMessageToMobile(String title, String content, String receiver) throws JSONException, ClientProtocolException, IOException {String source = "s-6bf44a17-73ba-45dc-9443-c34c5d53";//mi5s发送源idif (title.equals(null)) {title = "测试";}if (content.equals(null)) {content = "我是008!";}title = new String(title.getBytes(), "ISO-8859-1");//转换字符编码格式content = new String(content.getBytes(), "ISO-8859-1");//转换字符编码格式CloseableHttpClient httpClients = HttpClients.createDefault();//新建连接JSONObject jsonObject = new JSONObject();//新建json数组jsonObject.put("source", source.trim());//添加发送源idjsonObject.put("receiver", receiver.trim());//添加接收组idjsonObject.put("content", content.trim());//发送内容jsonObject.put("title", title.trim());//发送标题HttpPost httpPost = new HttpPost("https://api.alertover.com/v1/alert");//post请求接口StringEntity entity = new StringEntity(jsonObject.toString());//设置报文实体entity.setContentEncoding("ISO-8859-1");//设置编码格式entity.setContentType("application/json");//设置contentType,发送数据格式    httpPost.setEntity(entity);//设置请求实体    HttpResponse res = httpClients.execute(httpPost);//执行post请求,得到响应    if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//判断一下返回状态output("测试发送消息成功!");} else {HttpEntity httpEntity = res.getEntity();//获取响应实体output(httpEntity.toString());//输出相应实体}    httpClients.close();//关闭连接}