HttpClient发送Post请求,get请求

时间:2022-10-26 16:50:24
// 创建默认的httpclient实例
CloseableHttpClient httpclient = getHttpClient();
CloseableHttpResponse response = null;
// 创建httpPost
HttpPost httpPost = new HttpPost("url地址");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
try {
StringEntity param = new StringEntity(params, ContentType.APPLICATION_JSON);
httpPost.setEntity(param);
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream is = entity.getContent(); } } catch (Exception e) {
LOG.error("sendPostRequest error:", e);
} finally {
try {
//关闭连接,释放资源
response.close();
httpclient.close();
} catch (Exception e) {
LOG.error("HttpClient close error:", e);
}
}

发送Get请求

CloseableHttpClient httpclient = getHttpClient();
CloseableHttpResponse response = null;
HttpGet httpget = new HttpGet("url地址");
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream is = entity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//关闭连接,释放资源
response.close();
closeHttpClient(httpclient);
} catch (Exception e) {
LOG.error("HttpClient close error:", e);
}
}

借用某位大神的代码,只为日后方便查阅,请勿介意。