本人前幾天發現一款很好用的推送app——alertover,可是官網api的應用示例居然沒有java應用的示例,因此本身嘗試寫了一個。使用httpclient請求了一下post接口,傳了一下json數據,判斷一下響應的狀態碼。現分享代碼,共你們參考。java
public static void sendMessageToMobile(String title, String content, String receiver) throws JSONException, ClientProtocolException, IOException { String source = "s-6bf44a17-73ba-45dc-9443-c34c5d53";//mi5s發送源id if (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());//添加發送源id jsonObject.put("receiver", receiver.trim());//添加接收組id jsonObject.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();//關閉鏈接 }