Http请求工具

Http请求工具


GET,POST请求


import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
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.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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
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.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.*;public class HttpUtil {
    private static Certificate cert = null;
    private static SSLConnectionSocketFactory socketFactory;//私密连接工厂
    private static TrustManager manager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    /**
     * 是否忽略证书.https网站一般情况下使用了安全系数较低的SHA-1签名,因此首先我们在调用SSL之前需要重写验证方法,取消检测SSL。
     */
    private static void enableSSl(boolean isIgnore) {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            if (isIgnore) {
                context.init(null, new TrustManager[]{manager}, null);
            } else {
                context.init(null, new TrustManager[]{httpsManager}, null);
            }
            socketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier
                    .INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    /**
     * 证书获取
     *
     * @param certificateUrl 证书地址.
     */
    private static void initHttpsCertificate(String certificateUrl) {
        try {
            FileInputStream fis = new FileInputStream(certificateUrl);
            BufferedInputStream bis = new BufferedInputStream(fis);

            CertificateFactory cf = CertificateFactory.getInstance("X.509");

            while (bis.available() > 0) {
                cert = cf.generateCertificate(bis);
            }
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        }
    }

    private static TrustManager httpsManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String s) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{(X509Certificate) cert};
        }
    };

    /**
     * httpClient get http 请求.
     *
     * @param url    请求路径.
     * @param values 请求参数.
     * @return response 请求结果状态.
     */
    public static String doGet(String url, List<NameValuePair> values) throws IOException {
        RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        //最新版的httpClient使用实现类的是closeableHTTPClient,以前的default作废了.设置可关闭的httpclient
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
        StringBuilder urlBuffer = new StringBuilder(url);
        if (!url.contains("?")) {
            urlBuffer.append("?");
        }
        if (values != null) {
            for (NameValuePair nameValuePair : values) {
                urlBuffer.append("&").append(nameValuePair.getName()).append("=")
                        .append(URLEncoder.encode(nameValuePair.getValue(), "UTF-8"));
            }
        }

        HttpGet get = new HttpGet(urlBuffer.toString());
        CloseableHttpResponse response = httpClient.execute(get);
        return getResponseContent(response);
    }

    /**
     * httpClient post http 请求.
     *
     * @param url    请求路径.
     * @param values 请求参数.
     * @return response 请求结果状态.
     */
    public static String doPost(String url, List<NameValuePair> values) throws IOException {
        /*Map<String,String> paramMap = new HashMap<String, String>();
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        for (Map.Entry<String,String> entry : paramMap.entrySet()){
            formParams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }*/
        RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();

        HttpPost post = new HttpPost(url);

        if (values != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, "UTF-8");
            //StringEntity entity = new StringEntity(values);
            post.setEntity(entity);
        }
        CloseableHttpResponse response = httpClient.execute(post);
        return getResponseContent(response);

    }

    /**
     * httpClient post http 请求.
     *
     * @param url
     * @param values
     * @param charset
     * @return
     * @throws IOException
     */
    public static String doPost(String url, List<NameValuePair> values, String charset) throws IOException {
        RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();

        HttpPost post = new HttpPost(url);

        if (charset == null) {
            charset = "UTF-8";
        }

        if (values != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, charset);
            //StringEntity entity = new StringEntity(values);
            post.setEntity(entity);
        }
        CloseableHttpResponse response = httpClient.execute(post);
        return getResponseContent(response);

    }

    /**
     * httpClient get https 请求.
     *
     * @param url    请求路径.
     * @param values 请求参数.
     * @return response 请求结果状态.
     */
    public static String ignoreGetForHttps(String url, List<NameValuePair> values, boolean isIgnoreSSL) throws
            IOException {
        enableSSl(isIgnoreSSL);
        RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
                        AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
                .build();
        //创建可用Scheme
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
        //创建ConnectionManager,添加Connection配置信息
        PoolingHttpClientConnectionManager connectionManager = new
                PoolingHttpClientConnectionManager(socketFactoryRegistry);

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();

        StringBuilder urlBuffer = new StringBuilder(url);
        if (!url.contains("?")) {
            urlBuffer.append("?");
        }

        if (values != null) {
            for (NameValuePair nameValuePair : values) {
                urlBuffer.append("&").append(nameValuePair.getName()).append("=")
                        .append(URLEncoder.encode(nameValuePair.getValue(), "UTF-8"));
            }
        }

        HttpGet get = new HttpGet(urlBuffer.toString());

        CloseableHttpResponse response = httpClient.execute(get);

        return getResponseContent(response);
    }

    /**
     * httpClient get https 请求.
     *
     * @param url 请求路径.
     * @return response 请求结果状态.
     */
    public static String ignoreGetForHttps(String url, boolean isIgnoreSSL) throws
            IOException {
        enableSSl(isIgnoreSSL);
        RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
                        AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
                .build();
        //创建可用Scheme
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
        //创建ConnectionManager,添加Connection配置信息
        PoolingHttpClientConnectionManager connectionManager = new
                PoolingHttpClientConnectionManager(socketFactoryRegistry);

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();

        HttpGet get = new HttpGet(url);

        CloseableHttpResponse response = httpClient.execute(get);

        return getResponseContent(response);
    }    /**
     * httpClient post https 请求.
     *
     * @param url    请求路径.
     * @param values 请求参数.
     * @return response 请求结果状态.
     */
    public static String ignorePostForHttps(String url, List<NameValuePair> values, boolean isIgnoreSSL)
            throws IOException {
        enableSSl(isIgnoreSSL);
        //首先设置全局的标准cookie策略
        RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
                        AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
                .build();

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();

        PoolingHttpClientConnectionManager connectionManager = new
                PoolingHttpClientConnectionManager(socketFactoryRegistry);

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();

        HttpPost post = new HttpPost(url);

        if (values != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Charset.forName("UTF-8"));
            post.setEntity(entity);
        }
        CloseableHttpResponse response = httpClient.execute(post);
        return getResponseContent(response);
    }

    /**
     * 获取请求返回值.
     */
    private static String getResponseContent(CloseableHttpResponse response)
            throws IOException {
        StringBuilder returnBuffer = new StringBuilder();
        BufferedReader reader = null;
        try {
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = response.getEntity();
                httpEntity = new BufferedHttpEntity(httpEntity);
                return EntityUtils.toString(httpEntity);
            }
        } finally {
            response.close();
        }
        return null;
    }

}

转载于:https://www.cnblogs.com/lovellll/p/10222493.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/101222.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 改变Ubuntu18.04初始键盘布局

    改变Ubuntu18.04初始键盘布局改变 Ubuntu18 04 初始键盘布局安装 Ubuntu 的时候把键盘布局选择成了英文 英国 然后键盘符号就是一团糟 把 打成 很是难受 然后在网上搜索都是依靠代码调出的图形界面来处理 结果重启之后键盘又恢复了原来的样式 可能不适合我的情况吧 自己摸索了以下 发现很简单 用不到那些代码 设置 gt 区域和语言在输入源里选择英语 英国 点击 再点击 选择英语 美

    2025年6月12日
    0
  • 高级SQL查询-(聚合查询,分组查询,联合查询)[通俗易懂]

    高级SQL查询-(聚合查询,分组查询,联合查询)[通俗易懂]高级SQL查询-(聚合查询,分组查询,联合查询)

    2022年6月1日
    35
  • UVA 11464 Even Parity(递归枚举)

    UVA 11464 Even Parity(递归枚举)

    2022年1月10日
    47
  • DirectX修复工具常见问题解答

    DirectX修复工具常见问题解答经常有人在网上发帖询问DirectX修复工具的一些问题,但是有些问题的回答并不够准确。因此作者在这里把一些常见的问题列出,供大家参考。问题1:XP系统上运行软件时出现0xc0000135的错误,怎么回事?答:WindowsXPSP3系统用户需先安装Microsoft.NETFramework2.0或更高版本才可运行本程序,详情请见程序文件夹中的“致WindowsXP用户

    2022年5月29日
    192
  • 百度面试面经[通俗易懂]

    百度面试面经[通俗易懂]作者:球球球offer链接:https://www.nowcoder.com/discuss/230987来源:牛客网看到有帖子说百度的面经少,我发一下面经攒人品,许愿之后的面试都顺利!一共面了两

    2022年7月4日
    28
  • updog:一款局域网传输文件的软件

    updog:一款局域网传输文件的软件前言不知道你是否有过这样的需求,在局域网传输文件,苦于没有好的软件支持,或者只能单向传输,updog可以完全解决这种问题安装pip3installupdogupdog是python中的一个第三方库使用updog这里注意updog要在可以读写的路径下面运行,否则访问会出错,或者启动就会报错如果你不想切换到路径去运行,也可以使用-d去指定一个可读写的目录optiona…

    2022年5月29日
    42

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号