HttpClientUtil 开发

本文介绍了一个实用的HTTP客户端工具类,支持GET、POST、PUT和DELETE等HTTP方法,并能够发送JSON格式的数据。该工具类使用了Apache HttpClient库,提供了灵活的参数配置选项,如设置超时时间和身份验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

public class HttpClientUtil {
    
    private static final CloseableHttpClient httpClient;
    
    public static final String CHARSET = "UTF-8";

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    public static String doGet(String url, Map<String, String> params,String authority) {
        return doGet(url, params, CHARSET,authority);
    }

    public static String doPost(String url, Map<String, Object> params,String authority) {
        return doPost(url, params, CHARSET,authority);
    }

    public static String doPostWithJSON(String url, Object params,String authority) throws Exception {
        return doPostWithJSON(url, params, CHARSET,authority);
    }

    public static String doPutWithJSON(String url, Object params,String authority) throws Exception {
        return doPutWithJSON(url, params, CHARSET,authority);
    }

    public static String doDeleteWithJSON(String url, Object params,String authority) throws Exception {
        return doDeleteWithJSON(url, params, CHARSET,authority);
    }

    /**
     * Get 获取内容
     * @param url 请求的url地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @param authority 授权身份认证 可为空
     * @return 页面内容
     * @author wangaz
     * @Date 2018年9月18日 下午2:43:13
     */
    public static String doGet(String url, Map<String, String> params, String charset,String authority) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            if (StringUtil.isEmpty(authority)) {
                httpGet.setHeader("Authority", authority);
            }
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * HTTP Post 获取内容
     * @param url 请求的url地址
     * @param params
     * @param charset
     * @param authority
     * @return
     * @author wangaz
     * @Date 2018年9月18日 下午2:45:03
     */
    public static String doPost(String url, Map<String, Object> params, String charset,String authority) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<>(params.size());
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String value = String.valueOf(entry.getValue());
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            if (StringUtil.isEmpty(authority)) {
                httpPost.setHeader("Authority", authority);
            }
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * @param url
     * @param params
     * @param charset
     * @param authority
     * @return
     * @throws Exception
     * @author wangaz
     * @Date 2018年9月18日 下午2:45:23
     */
    public static String doPostWithJSON(String url, Object params, String charset,String authority) throws Exception {
        HttpPost httpPost = new HttpPost(url);

        StringEntity entity = new StringEntity(JSON.toJSONString(params), charset);
        entity.setContentEncoding(charset);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        if (StringUtil.isEmpty(authority)) {
            httpPost.setHeader("Authority", authority);
        }
        
        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity responseEntity = response.getEntity();
        String respContent = EntityUtils.toString(responseEntity, charset);
        return respContent;
    }

    /**
     * 
     * @param url
     * @param params
     * @param charset
     * @param authority
     * @return
     * @throws Exception
     * @author wangaz
     * @Date 2018年9月18日 下午2:45:35
     */
    public static String doPutWithJSON(String url, Object params, String charset,String authority) throws Exception {
        HttpPut httpPut = new HttpPut(url);

        StringEntity entity = new StringEntity(JSON.toJSONString(params), charset);
        entity.setContentEncoding(charset);
        entity.setContentType("application/json");
        httpPut.setEntity(entity);
        if (StringUtil.isEmpty(authority)) {
            httpPut.setHeader("Authority", authority);
        }
        HttpResponse response = httpClient.execute(httpPut);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPut.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity responseEntity = response.getEntity();
        String respContent = EntityUtils.toString(responseEntity, charset);
        return respContent;
    }

    /**
     * 
     * @param url
     * @param params
     * @param charset
     * @param authority
     * @return
     * @throws Exception
     * @author wangaz
     * @Date 2018年9月18日 下午2:45:41
     */
    public static String doDeleteWithJSON(String url, Object params, String charset,String authority) throws Exception {
        /**
         * 没有现成的delete可以带json的,自己实现一个,参考HttpPost的实现
         */
        class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
            public static final String METHOD_NAME = "DELETE";

            @SuppressWarnings("unused")
            public HttpDeleteWithBody() {
            }

            @SuppressWarnings("unused")
            public HttpDeleteWithBody(URI uri) {
                setURI(uri);
            }

            public HttpDeleteWithBody(String uri) {
                setURI(URI.create(uri));
            }

            public String getMethod() {
                return METHOD_NAME;
            }
        }
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);

        StringEntity entity = new StringEntity(JSON.toJSONString(params), charset);
        entity.setContentEncoding(charset);
        entity.setContentType("application/json");
        httpDelete.setEntity(entity);
        if (StringUtil.isEmpty(authority)) {
            httpDelete.setHeader("Authority", authority);
        }
        HttpResponse response = httpClient.execute(httpDelete);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpDelete.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity responseEntity = response.getEntity();
        String respContent = EntityUtils.toString(responseEntity, charset);
        return respContent;
    }


}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值