post请求方式写法
程序员文章站
2022-04-14 12:46:38
...
public static String send(String url,String data) throws DJException{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = null;
CloseableHttpResponse response=null;
try {
post = new HttpPost(url); // 请求方法Post
StringEntity entity = new StringEntity(data,"utf-8");
entity.setContentEncoding("UTF-8"); // 字符编码
entity.setContentType("application/json"); // json类型
post.setEntity(entity);
response =httpClient.execute(post);
int statusCode= response.getStatusLine().getStatusCode(); // 返回的状态码
if(statusCode == 200) {
HttpEntity he = response.getEntity();
return EntityUtils.toString(he, "UTF-8");
}else{
throw new DJException("服务器连接异常statusCode:"+statusCode);
}
} catch (IOException e) {
e.printStackTrace();
throw new DJException("请求失败:"+e.getMessage());
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
}
}
}