public class ElephantServiceImpl implements ElephantService { public final static String url = "http://dxw-in.sankuai.com/api/pub/push"; public final static String client_id = "xxxxxxxxxx"; public final static String client_secret = "xxxxxxxxxx"; public boolean send(List<String> receivers, String body, String sender, String type) { try { String rfc1123Date = SignatureUtils.getRfc1123Pattern(); String authorization = SignatureUtils.getAuthorizationHeader(rfc1123Date,url,client_id,client_secret); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json;charset=utf-8"); httpPost.setHeader("Date",rfc1123Date); httpPost.setHeader("Authorization",authorization); String json = constructJson(receivers, body, sender, type); StringEntity paraEntity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(paraEntity); CloseableHttpResponse response = httpclient.execute(httpPost); String responseContent = null; // 响应内容 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseContent); } response.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } private String constructJson(List<String> receivers, String body, String sender, String type) { String json = "{\"sender\":\"" + sender + "\", \"receivers\":" + receivers.toString() + ", \"body\": \"" + body + "\",\"messageType\":\"" + type + "\"} "; return json; } }
HttpComponent-HttpClient使用-发送Post请求
最新推荐文章于 2024-06-21 09:59:40 发布