https封装类,支持get/post请求

所需jar:commons-logging-1.1.3.jar、httpclient-4.3.1.jar、httpcore-4.3.jar

package com.onlyou.microfinance.common.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

/**
 * https封装类,支持get、post
 *
 * @author Administrator
 *
 */
public class HttpsUtil {
    private static CloseableHttpClient client=null;

    private static CloseableHttpClient createHttpsClient() {
        if(client!=null){
            return client;
        }
        try {
            X509TrustManager x509mgr = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String string) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String string) {
                }

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

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509mgr}, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

             client=HttpClients.custom().setSSLSocketFactory(sslsf).build();
             return client;
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    public static HttpEntity doGetByHttps(String url, String host, String cacheControl, String contentType,
            String acceptCharset, String pragma, String accept, String acceptEncoding, String referer) throws Exception {
        CloseableHttpClient client = createHttpsClient();
        HttpHost httpHost = new HttpHost(host, 443, "https");
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
        httpGet.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
        httpGet.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset);
        httpGet.addHeader(HttpHeaders.PRAGMA, pragma);
        httpGet.addHeader(HttpHeaders.ACCEPT, accept);
        httpGet.addHeader(HttpHeaders.ACCEPT_ENCODING, acceptEncoding);
        httpGet.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2471.0 Safari/537.36");
        httpGet.addHeader(HttpHeaders.REFERER, referer);
        HttpResponse response = client.execute(httpHost, httpGet);
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            //String result = EntityUtils.toString(httpEntity);
            //byte[] data = EntityUtils.toByteArray(httpEntity);
            return entity;
        } else {
            return null;
        }
    }

    public static HttpEntity doGetByHttps(String url, String host, String contentType, String referer) throws Exception {
        return doGetByHttps(url, host, "no-cache", contentType, "utf-8", "no-cache",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "gzip, deflate, sdch", referer) ;
    }

    public static HttpEntity doPostByHttps(String url, String host, String cacheControl, String contentType,
            String acceptCharset, String pragma, String accept, String acceptEncoding, String referer, Map<String, Object> paramMap) {
        HttpHost httpHost = new HttpHost(host, 443, "https");
        HttpPost httpRequst = new HttpPost(url);
        httpRequst.addHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
        httpRequst.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
        httpRequst.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset);
        httpRequst.addHeader(HttpHeaders.PRAGMA, pragma);
        httpRequst.addHeader(HttpHeaders.ACCEPT, accept);
        httpRequst.addHeader(HttpHeaders.ACCEPT_ENCODING, acceptEncoding);
        httpRequst.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2471.0 Safari/537.36");
        httpRequst.addHeader(HttpHeaders.REFERER, referer);

        List<NameValuePair> params = new ArrayList<>();
        if (paramMap != null && !paramMap.isEmpty()) {
            for (String key : paramMap.keySet()) {
                params.add(new BasicNameValuePair(key, (String) paramMap.get(key)));
            }
        }

        try {
            httpRequst.setEntity(new UrlEncodedFormEntity(params));
            CloseableHttpClient client = createHttpsClient();
            HttpResponse httpResponse = client.execute(httpHost, httpRequst);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                //String result = EntityUtils.toString(httpEntity);
                //byte[] data = EntityUtils.toByteArray(httpEntity);
                return httpEntity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static HttpEntity doPostByHttps(String url, String host, String contentType, String referer, Map<String, Object> paramMap) throws Exception {
        return doPostByHttps(url, host, "no-cache", contentType, "utf-8", "no-cache",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "gzip, deflate, sdch", referer, paramMap) ;
    }
}

调用示例:

HttpEntity loginEntity = HttpsUtil.doPostByHttps(url, "ipcrs.pbccrc.org.cn", "application/x-www-form-urlencoded", "https://*/page/login/loginreg.jsp", map);

HttpEntity entity = HttpsUtil.doGetByHttps(url, host, "image/jpeg", "https://*/page/login/loginreg.jsp");
时间: 2024-10-03 04:02:10

https封装类,支持get/post请求的相关文章

Spring Boot如何让某个Controller支持跨源请求,以及如何让Controller类某个成员方法支持跨源请求

在前面我们已经讨论了Spring Boot 如何全局支持跨源请求.如果你想了解可以查看这篇文章 下面我们讨论另一种场景.有些时候,你需要让你的应用在大部分的时候,仅仅支持当前域名下的请求.而仅仅在极其特殊的几个场合下,才支持跨源请求.这个时候,你需要把跨源请求仅仅缩小在几个Controller上,或者Controller类的几个成员方法上.这个时候你需要用到如下的注解:@CrossOrigin(origins = "*", maxAge = 3600) .把这个注解放到 Control

django 实现全局支持跨域请求

Django 允许跨域请求 一.django 实现支持跨域请求,本人所了解到的方法有两种: 1.视图中进行配置,只实现当前视图支持跨域请求 2.进行全局配置,实现所有视图均支持跨域请求 这里对第二种方法进行一下说明: 1.安装django-cors-headers pip install django-cors-headers 2.配置settings.py文件 INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE_CLASSES = (

Chrome不支持本地Ajax请求,解决办法

Chrome不支持本地Ajax请求,当我在.html文件中访问.json文件时就会出现这个问题,就是说这个时候不能加载这个.html文件. 解决方式 打开Chrome快捷方式的属性中设置: 右击Chrome浏览器快捷方式,选择"属性", 在"目标"中加上"--allow-file-access-from-files",注意前面有个空格, 重启Chrome浏览器便可.

ANTS Performance Profiler 8:支持对Web请求、异步代码和WinRT的性能剖析

下载与激活:http://download.csdn.net/detail/lone112/6734291 离线激活 位于英国的Red Gate Software有限公司最近发布了ANTS Performance Profiler 8 Beta,支持对Web请求.异步代码和Windows商店应用的性能剖析.该版本还支持SharePoint 2013和一个新的时间线,这使开发者不但能够监控应用程序的性能,还能深入到想要检查的具体区域. Web请求剖析使开发者能够捕获向外的HTTP请求,其中包括请求

Chrome不支持本地Ajax请求解决?

今天用JQuery操作Ajax时,使用load方法加载html块 结果提示: XMLHttpRequest cannot load file~~~~~~~Origin 'null' is therefore not allowed access 原因如下: Chrome不支持本地Ajax请求,当我在.html文件中访问使用load方法加载文件时就会出现这个问题,就是说这个时候不能加载这个.html文件. 解决方式 打开Chrome快捷方式的属性中设置: 右击Chrome浏览器快捷方式,选择“属性

自己实现简单Web服务器,支持GET POST请求

最近项目上遇到一个需求,最后想到的解决方案是自己实现一个web服务器去处理请求,然后再将信息发送到另外一个程序.然后返回处理之后的结果呈现出来. 现在我就来分享一下如何实现的. 通过.NET 为我们提供的HttpListener类实现对Http协议的处理,实现简单的web服务器. 注意:此类在 .NET Framework 2.0 版中是新增的.所以支持.NET Framework 2.0以上版本.该类仅在运行 Windows XP SP2 或 Windows Server 2003 操作系统的

Chrome浏览器不支持本地Ajax请求的解决方案

问题描述: 通过Ajax获取本地JSON文件时候,报Received an invalid response. Origin 'null' is therefore not allowed access. 错误. 原因: Chrome浏览器不支持本地Ajax请求,当在html文件中使用Ajax时候,就报错. 解决方案: 右击chrome浏览器快捷方式图标,选择属性,在目标中添加:--allow-file-access-from-files,与chrome.exe之前有个空格.

libcurl的封装,支持同步异步请求,支持多线程下载,支持https

最近在做一个项目,需要用到http get post等 需求分析需要做到同步和异步,异步请求的返回以可选的回调通知的方式进行. 本人以Linux为例,一步一步的来实现. 配置并且编译libcurl我以在Linux底下的交叉编译举例.libcurl源码下载: http://curl.haxx.se/download.html配置libcurl支持https和zlib压缩,必须需要openssl和zlib库openssl库源码下载: http://www.openssl.org/source/.下载

webapi 支持 text/plain 请求

今天遇到一个需求,请求以HTTPS + XML 访问我的API ,普通的webapi 是不支持这个请求的,故做以下代码进行支持 新增一个类,类名为PlainTextTypeFormatter public class PlainTextTypeFormatter : MediaTypeFormatter { public PlainTextTypeFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain&