HTTPclient工具类

httpclient简介

httpclient是apache旗下的一款开源Java组件,现在放在Apache HttpComponents里面进行维护,用来提供高效的、最新的、功能丰富的支持. HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HTTPclient和浏览器有点像,但是确不是浏览器,它实际上是一个HTTP通信库,它只提供一个通用浏览器应用程序所期望的功能子集。httpclient只能以编程的方式通过其API用于传输和接受HTTP消息。

HTTPclient主要的功能

  • 实现了所有HTTP的方法(GET、POST、PUT、DELETE、HEAD、OPTIONS、PATCH等)
  • 支持https协议
  • 支持代理服务器(nginx)等
  • 支持自动(跳转)转向
  • ......

本文以springboot项目示例,所以首先需要在pom文件中引入

        <dependency>
            <groupId>Maven.org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
        </dependency>

接下来主要构造了四个http请求方法,包括get/post/put/delete等四种方式,分别封装在一个工具类中,详细代码可参考github: https://github.com/chenxiangweifeng/study 主要在HttpClientUtil类里。

/**
 * @author 沉香微风
 * httpclient工具类
 * 增删改查 put post delete get 四种常用的请求方式工具类
 */
public class HttpClientUtil {

    private static String doPost(String url, String jsonText) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = null;
        String result = "";
        try {
            System.out.println("发送post请求");
//            这里需要将一个Java中的对象转换为web前端发送的json字符串对象,
            StringEntity entity = new StringEntity(jsonText, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            System.out.println("http get io 异常发生了");
        } finally {
            try {
                System.out.println("释放资源、关闭连接");
                if (httpPost != null) {
                    httpPost.releaseConnection();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    ((CloseableHttpResponse) response).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 发起httpget请求
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {
        System.out.println(url);
        String result = "";
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println("释放资源、关闭httpget连接");
                if (httpClient != null) {
                    httpGet.releaseConnection();
                }
                if (httpClient != null) {
                    ((CloseableHttpClient) httpClient).close();
                }
                if (response != null) {
                    ((CloseableHttpResponse) response).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发起httpdelete请求
     *
     * @param url
     * @return
     */
    public static String doDelete(String url) {
        String result = "";
        HttpDelete httpDelete = new HttpDelete(url);
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpDelete);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println("释放资源、关闭httpdelete连接");
                if (httpClient != null) {
                    httpDelete.releaseConnection();
                }
                if (httpClient != null) {
                    ((CloseableHttpClient) httpClient).close();
                }
                if (response != null) {
                    ((CloseableHttpResponse) response).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * http put 请求
     * @return
     * @throws Exception
     */
    private static String doPut(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        HttpResponse response = null;
        String result = "";
        try {
            System.out.println("发送put请求");
            response = httpClient.execute(httpPut);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            System.out.println("http put io 异常发生了");
        }finally {
            try {
                System.out.println("释放资源、关闭连接 put请求");
                if(httpPut != null){
                    httpPut.releaseConnection();
                }
                if(httpClient != null){
                    httpClient.close();
                }
                if(response != null){
                    ((CloseableHttpResponse) response).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
posted @ 2020-11-03 15:48  沉香微风  阅读(768)  评论(0)    收藏  举报