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

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • CSP考试总结_考试总结300字

    CSP考试总结_考试总结300字t1模拟很难受,要加大这方面练习,要习惯用草稿理清思路t2和去年一样的东西,也是高精的坑,考前应该补一下高精t3比较正常,这种大数据结构只有考虑暴力,打正解很容易浪费时间并且上头t4无能

  • 安卓系统能读ntfs文件吗(Android Pie)

    AndroidP支持NTFS读取KernelConfigCONFIG_NTFS_FSCONFIG_NTFS_RW(只能针对已存在文件进行写操作)CONFIG_NLSCONFIG_NLS_UTF8(用于支持中文格式)vold修改文件:fs文件夹追加Ntfs.cpp和Ntfs.h,可以以Exfat.cpp为模板。差异点:fs/Ntfs.cpp①IsSupported直接returnIsFileSystemSupported(“ntfs”)。②Check函数直接返回0。③Mount函

  • apache 负载均衡策略_负载均衡slb

    apache 负载均衡策略_负载均衡slb参考文章:http://www.2cto.com/os/201109/102368.html在观看本文章之前,请先观看apache负载均衡之配置:http://blog.csdn.net/a787031584/article/details/64907389apache负载均衡策略有三种:第一种:轮询策略:即根据http请求数(requests)来均衡的分配给所代理的服

  • keyvaluepair_C# KeyValuePair<TKey,TValue>的用法【转】 .

    keyvaluepair_C# KeyValuePair<TKey,TValue>的用法【转】 .KeyValuePair可以这样实例化KeyValuePairmcmillan=newKeyValuePair(“McMillan”,99);取值Console.Write(mcmillan.Key);Console.Write(“”+mcmillan.Value);以下是一个把对象放到数组中usingSystem;usingSystem.Collections.Generic…

  • XXE漏洞原理[通俗易懂]

    XXE漏洞原理[通俗易懂]XXE漏洞是XML外部实体注入漏洞,那什么是外部实体呢?XMLDTD1、文档类型定义(DTD)可定义合法的XML文档构建模块。它使用一系列合法的元素来定义文档的结构。2、DTD可被成行地声明于XML文档中,也可作为一个外部引用。Ps:第二条是重点,也是XXE漏洞产生的原因,DTD可以定义外部实体并引用DTD语法若DTD要在XML文档中使用,他需要包含在·DOCTYPE声明…

  • row_number() OVER (PARTITION BY COL1 ORDER BY COL2)「建议收藏」

    row_number() OVER (PARTITION BY COL1 ORDER BY COL2)

发表回复

您的电子邮箱地址不会被公开。

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