网络请求HttpClientHelper实现

  1. HttpClientHelper
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class HttpClientHelper {
    private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
    private static HttpClientHelper instance = null;
    private static Lock lock = new ReentrantLock();
    private static CloseableHttpClient httpClient;

    public HttpClientHelper() {
        instance = this;
    }

    public static HttpClientHelper getHttpClient() {
        if (instance == null) {
            lock.lock();
            try {
                instance = new HttpClientHelper();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        return instance;
    }

    public void init() {
        PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
        pool.setMaxTotal(500);
        pool.setDefaultMaxPerRoute(50);
        httpClient = HttpClientBuilder.create().setConnectionManager(pool).build();
    }

    public byte[] executeAndReturnByte(HttpRequestBase request) throws Exception {
        HttpEntity entity = null;
        CloseableHttpResponse response = null;
        byte[] base = new byte[0];
        if (request == null) {
            return base;
        }
        if (httpClient == null) {
            init();
        }
        if (httpClient == null) {
            logger.error("http获取异常");
            return base;
        }
        response = httpClient.execute(request);
        entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200) {
            String encode = ("" + response.getFirstHeader("Content-Encoding")).toLowerCase();
            if (encode.indexOf("gzip") > 0) {
                entity = new GzipDecompressingEntity(entity);
            }
            base = EntityUtils.toByteArray(entity);
        } else {
            logger.error("" + response.getStatusLine().getStatusCode());
        }
        EntityUtils.consumeQuietly(entity);
        response.close();

        return base;
    }

    public String execute(HttpRequestBase request) throws Exception {
        byte[] base = executeAndReturnByte(request);
        if (base == null) {
            return null;
        }
        return new String(base, StandardCharsets.UTF_8);
    }
}
  1. 调用HttpUtil实现
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    private static String UTF8 = "UTF-8";
    private static RequestConfig requestConfig;

    public static boolean isRequestSuccessful(HttpResponse httpresponse) {
        return httpresponse.getStatusLine().getStatusCode() == 200;
    }

    public static String get(String url) throws Exception {
        HttpGet get = null;
        get = new HttpGet(url);
        return HttpClientHelper.getHttpClient().execute(get);
    }

    public static String get(Map<String, String> header, String url) throws Exception {
        HttpGet get = null;
        get = new HttpGet(url);
        if (header != null) {
            for (String key : header.keySet()) {
                get.addHeader(key, header.get(key));
            }
        }
        return HttpClientHelper.getHttpClient().execute(get);
    }

    public static String post(Map<String, String> header, Map<String, String> params, String url) throws Exception {
        HttpPost post = null;
        post = new HttpPost(url);
        if (header != null) {
            for (String key : header.keySet()) {
                post.addHeader(key, header.get(key));
            }
        }
        if (params != null) {
            List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
            post.setConfig(getRequestConfig());
            for (String key : params.keySet()) {
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, UTF8);
            post.setEntity(entity);
        }
        return HttpClientHelper.getHttpClient().execute(post);
    }

    public static String post(Map<String, String> header, String jsonObject, String url) throws Exception {
        HttpPost post = null;
        post = new HttpPost(url);
        if (header != null) {
            for (String key : header.keySet()) {
                post.addHeader(key, header.get(key));
            }
        }
        if (jsonObject.isEmpty()) {
            throw new Exception("jsonObject不能为空!");
        }
        HttpEntity entity = new StringEntity(jsonObject, ContentType.APPLICATION_JSON.toString(), "UTF-8");
        post.setEntity(entity);
        return HttpClientHelper.getHttpClient().execute(post);
    }

    public static String post(MultipartFile file, Map<String, String> header, String url) throws Exception {
        HttpPost post = new HttpPost(url);
        if (MapUtils.isNotEmpty(header)) {
            for (String key : header.keySet()) {
                post.addHeader(key, header.get(key));
            }
        }
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
        builder.addBinaryBody("file", file.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());// 文件流
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        return HttpClientHelper.getHttpClient().execute(post);
    }

    public static String post(String jsonObjectStr, String url) throws Exception {
        HttpPost post = null;
        post = new HttpPost(url);
        if (jsonObjectStr.isEmpty()) {
            throw new Exception("jsonObjectStr不能为空!");
        }
        HttpEntity entity = new StringEntity(jsonObjectStr, "UTF-8");
        post.setEntity(entity);
        return HttpClientHelper.getHttpClient().execute(post);
    }

    public static String post(Map<String, String> params, String url) throws Exception {
        HttpPost post = null;
        post = new HttpPost(url);
        List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
        post.setConfig(getRequestConfig());
        for (String key : params.keySet()) {
            list.add(new BasicNameValuePair(key, params.get(key)));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, UTF8);
        post.setEntity(entity);
        return HttpClientHelper.getHttpClient().execute(post);
    }

    public static RequestConfig getRequestConfig() {
        if (requestConfig == null) {
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)
                    .setConnectTimeout(20000).setSocketTimeout(20000).build();
        }
        return requestConfig;
    }

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client_IP");
        }
        if (ip == null || ip.length() == 0 || "unkonwn".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.length() < 5) {
            ip = "0.0.0.0";
        }
        return ip;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值