HttpClient-GET|POST|DELETE|PUT 使用

使用HttpClient编写http请求工具类

工具类目前支持GET|POST|DELETE|PUT,而且可以设置请求入参

本工具类的核心就是提纯了一个 execute 方法,使每种请求的方式代码都保持在两三行左右,感觉还行。分享一下

废话不多说,上代码,pom引用,测试类。本人一直在用,亲测好用

代码
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Slf4j
public class HttpUtil {

    public static Header[] DEFAULT_HEADERS = { new BasicHeader("Content-type", "application/json"),new BasicHeader("DataEncoding", "UTF-8")};

    /**
     * 发送原生put请求
     * <br/>
     *
     * @param url                      请求的url
     * @param jsonStr                  请求的参数,json格式
     * @param connectionTimeout        连接建立时间,三次握手时间(毫秒)
     * @param connectionRequestTimeout 从连接池获取连接的超时时间(毫秒)
     * @param socketTimeout            传输过程中数据包间隔最大时间(毫秒)
     * @return java.lang.String 	   返回结果
     * @author jamel.li
     * @date 2019/11/22 15:32
     */
    public static String doPut(String url, String jsonStr, int connectionTimeout, int connectionRequestTimeout, int socketTimeout) {
        try {
            HttpPut httpRequest = new HttpPut(url);
            httpRequest.setEntity(new StringEntity(jsonStr));
            return execute(httpRequest, DEFAULT_HEADERS, connectionTimeout, connectionRequestTimeout, socketTimeout);
        } catch (UnsupportedEncodingException e) {
            log.error("", e.toString());
        }
        return null;
    }

    /**
     * 发送原生delete请求
    */
    public static String doDelete(String url, int connectionTimeout, int connectionRequestTimeout, int socketTimeout) {
        return execute(new HttpDelete(url), DEFAULT_HEADERS, connectionTimeout, connectionRequestTimeout, socketTimeout);
    }

    /**
     * 发送原生put请求
     */
    public static String doPost(String url, String jsonStr, int connectionTimeout, int connectionRequestTimeout, int socketTimeout) {
        try {
            HttpPost httpRequest = new HttpPost(url);
            httpRequest.setEntity(new StringEntity(jsonStr));
            return execute(httpRequest, DEFAULT_HEADERS, connectionTimeout, connectionRequestTimeout, socketTimeout);
        } catch (UnsupportedEncodingException e) {
            log.error("", e.toString());
        }
        return null;
    }

    /**
     * 发送原生get请求
     */
    public static String doGet(String url, int connectionTimeout, int connectionRequestTimeout, int socketTimeout) {
        return execute(new HttpGet(url), DEFAULT_HEADERS, connectionTimeout, connectionRequestTimeout, socketTimeout);
    }

    /**
     * 执行 request
     */
    public static String execute(HttpRequestBase request, Header[] headers, int connectionTimeout, int connectionRequestTimeout, int socketTimeout) {

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();
        request.setConfig(requestConfig);
        request.setHeaders(headers);

        //创建客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            //执行请求
            httpResponse = httpClient.execute(request);
            //得到返回结果
            HttpEntity entity = httpResponse.getEntity();

            return EntityUtils.toString(entity);

        } catch (ClientProtocolException e) {
            log.error("", e.toString());
        } catch (IOException e) {
            log.error("", e.toString());
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    log.error("", e.toString());
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("", e.toString());
                }
            }
        }
        return null;
    }
pom 需要的引用
		<!-- log 需要记log就集成这个-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j}</version>
        </dependency>
        
        <!-- log 需要使用@Slf4j 就集成这个-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

        <!-- httpClient相关 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.5</version>
        </dependency>

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

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.48</version>
        </dependency>
一般情况下如果json字符串入参都需要做转换,url返回结果也需要转换成需要的对象。可以参考下面的测试类
测试类
public class HttpUtilTest {

    public static void main(String[] args) {
		testDoPut();
    }

    public static void testDoPut() {
        String url = "http://127.0.0.1:9200/_snapshot/es_backup/123";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("indices", "kafkalog-ea-xl-sysmanage-2019-11-18");
        Integer connectionTimeout = 60000;//毫秒 链接建立时间
        Integer connectionRequestTimeout = 600000;//毫秒 请求时间
        Integer socketTimeout = 600000;//毫秒 链接建立时间
        String result = HttpUtil.doPut(url, JSONObject.toJSONString(paramMap), connectionTimeout, connectionRequestTimeout, socketTimeout);
        //Map<String, Object> jsonObject = (Map<String, Object>) JSONObject.parse(searchResult);
        System.out.println(result);
    }

如果有更好的修改建议,欢迎指出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值