您的位置:首页 > 理论基础 > 计算机网络

HttpComponent-HttpClient使用-发送Post请求

2016-06-28 15:02 501 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: