Httpclient4的http请求封装

1. 实现 httpheader

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.ParseException;

/**
 * Demo class
 *
 * @author Muxin Sun
 * @date 2019/10/01
 */
public class HttpHeader implements Header {
    
    private String name;
    private String value;
    
    public HttpHeader(String name, String value) {
        this.name = name;
        this.value = value;
    }

    @Override
    public HeaderElement[] getElements() throws ParseException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return name;
    }

    @Override
    public String getValue() {
        // TODO Auto-generated method stub
        return value;
    }
}

2. 实现 http 请求封装

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.Header;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import static com.neusoft.rsapm.brain.common.inter.message.Message.SUCCESS_CODE;

/**
 * HTTP visit class for http request
 *
 * @author Muxin Sun
 * @date 2019/10/01
 */
public class HttpUtil {
    
    private static final String CHARSET = "utf-8";
    private static final String CONTENT_TYPE = "application/json";

    public static final String REMOTE_ADDR="remoteAddr";
    public static final String REMOTE_PORT="remotePort";

    public static String getRemoteAddr(HttpServletRequest request) {
        return Objects.nonNull(request.getHeader(REMOTE_ADDR)) ? request.getHeader(REMOTE_ADDR) : request.getRemoteAddr();
    }

    public static String getRemotePort(HttpServletRequest request) {
        return Objects.nonNull(request.getHeader(REMOTE_PORT)) ? request.getHeader(REMOTE_PORT) : String.valueOf(request.getRemotePort());
    }

    public static CloseableHttpClient getHttpClient() {
        return getHttpClient(null);
    }
    
    public static CloseableHttpClient getHttpClient(HttpHost proxy) {
        
        CloseableHttpClient client = null;
        
        try {
            SSLContext sslcontext = createIgnoreVerifySSL();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext, new DefaultHostnameVerifier())).build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CredentialsProvider provider = new BasicCredentialsProvider();
            if (proxy!=null) {
                client = HttpClients.custom().setConnectionManager(connManager).setProxy(proxy).build();
            } else {
                client = HttpClients.custom().setConnectionManager(connManager).build();
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return client;
    }

    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
    
    public static String HttpGET(String url) throws IOException {
        return HttpGET(url, new ArrayList<>());
    }
    
    public static String HttpGET(String url, List<Header> headers) throws IOException {
        return HttpGET(url, headers, null);
    }

    public static String HttpGET(String url, HttpHost proxy) throws IOException {
        return HttpGET(url, new ArrayList<>(), proxy);
    }

    public static String HttpGET(String url, List<Header> headers, HttpHost proxy) throws IOException {
        final CloseableHttpClient client = getHttpClient(proxy);

        HttpGet get = new HttpGet(url);
        headers.forEach(header -> {
            get.addHeader(header.getName(), header.getValue());
        });
        get.addHeader(HTTP.CONTENT_ENCODING, CHARSET);
        get.addHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE);
        CloseableHttpResponse resp = client.execute(get);

        if (resp.getStatusLine().getStatusCode() != SUCCESS_CODE) {
            return null;
        }

        HttpEntity entity = resp.getEntity();
        Scanner sin = new Scanner(EntityUtils.toString(entity));
        entity.getContent();

        StringBuilder res = new StringBuilder();
        while(sin.hasNext()) {
            res.append(sin.nextLine());
        }

        sin.close();
        resp.close();
        client.close();

        return res.toString();
    }

    public static String HttpPOST(String url, String body) throws IOException {
        return HttpPOST(url, body, null);
    }

    public static String HttpPOST(String url, String body, HttpHost proxy) throws IOException {
        return HttpPOST(url, new ArrayList<>(), body, CHARSET, CONTENT_TYPE, proxy);
    }
    
    public static String HttpPOST(String url, List<Header> headers, String body) throws IOException {
        return HttpPOST(url, headers, body, CHARSET, CONTENT_TYPE, null);
    }

    public static String HttpPOST(String url, List<Header> headers, String body, HttpHost proxy) throws IOException {
        return HttpPOST(url, headers, body, CHARSET, CONTENT_TYPE, proxy);
    }

    public static String HttpPOST(String url, List<Header> headers, Map<String, Object> params) throws IOException {
        return HttpPOST(url, headers, params, null);
    }
    
    public static String HttpPOST(String url, List<Header> headers, Map<String, Object> params, HttpHost proxy) throws IOException {
        JSONObject body = new JSONObject();
        params.forEach(body::put);
        return HttpPOST(url, headers, body.toString(), proxy);
    }

    public static String HttpPOST(String url, List<Header> headers, List<Map<String, Object>> params) throws IOException {
        return HttpPOST(url, headers, params, null);
    }
    
    public static String HttpPOST(String url, List<Header> headers, List<Map<String, Object>> params, HttpHost proxy) throws IOException {
        JSONArray body = new JSONArray();
        params.forEach(param -> {
            JSONObject jObj = new JSONObject();
            param.forEach(jObj::put);
            body.add(jObj);
        });
        return HttpPOST(url, headers, body.toString(), proxy);
    }

    public static String HttpPOST(String url, List<Header> headers, String body, String charset, String contentType, HttpHost proxy) throws IOException {
        final CloseableHttpClient client = getHttpClient(proxy);
        HttpPost post = new HttpPost(url);
        post.addHeader(HTTP.CONTENT_ENCODING, charset);
        post.addHeader(HTTP.CONTENT_TYPE, contentType);
        headers.forEach(header -> {
            if(!header.getName().toLowerCase().equals(HTTP.CONTENT_LEN.toLowerCase())) {
                post.addHeader(header.getName(), header.getValue());
            }
        });
        post.setEntity(new StringEntity(String.valueOf(body), charset));
        CloseableHttpResponse resp = client.execute(post);
        if (resp.getStatusLine().getStatusCode() != SUCCESS_CODE) {
            return null;
        }
        
        HttpEntity entity = resp.getEntity();
        Scanner sin = new Scanner(EntityUtils.toString(entity));
        entity.getContent();
        
        StringBuilder res = new StringBuilder();
        while(sin.hasNext()) {
            res.append(sin.nextLine());
        }
        
        sin.close();
        resp.close();
        client.close();

        return res.toString();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • AFHTTPRequestOperationManager 网络传输协议UDP、TCP、Http、Socket、X...
    Carden阅读 4,319评论 0 12
  • 1. 前言 Linux下的http请求有许多种方式,其中curl库是C语言封装的一个强大的库,使用curl比封...
    星夜兼程工作笔记阅读 4,557评论 0 0
  • AJAX 原生js操作ajax 1.创建XMLHttpRequest对象 var xhr = new XMLHtt...
    碧玉含香阅读 3,170评论 0 7
  • 组织:中国互动出版网(http://www.china-pub.com/) RFC文档中文翻译计划(http://...
    Palomar阅读 1,561评论 0 6
  • 听到了你的声音 我知道你在向我靠近 可为什么 你不让我看见 弄得我心神不宁 我只能假装不知道 用半裸的身体来勾引你...
    浅梦轻轻阅读 261评论 2 12