java Https工具类

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * https工具类
 *
 * @author remainsu
 * 2019-05-05
 */
public class HttpsUtil {

    /**
     * post方式访问
     * @param url 路径
     * @param map 参数
     * @return
     */
    public String httpsPost(String url, Map<String, String> map) {

        String charset = "UTF-8";
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;

        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * get方式访问(如果有参数直接 ?xx&yy&zz 的方式即可)
     * @param url
     * @return
     */
    public String httpsGet(String url) {

        String charset = "UTF-8";
        HttpClient httpClient = null;
        HttpGet httpGet= null;
        String result = null;

        try {
            httpClient = new SSLClient();
            httpGet = new HttpGet(url);

            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}

class SSLClient extends DefaultHttpClient {
    //用于进行Https请求的HttpClient
    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {return null; }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

原文地址:https://www.cnblogs.com/remainsu/p/java-https-gong-ju-lei.html

时间: 2024-08-27 00:19:12

java Https工具类的相关文章

java常用工具类(三)—— Excel 操作工具

import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; i

zookeeper-kafka(集群版)安装部署以及java调用工具类

Kafka安装部署文档 ■ 文档版本 V1.0 ■ 操作系统 CentOS Linux release 7.3.1611 ■ 编写人员 闫立雄 ■ 文档日期 2019-01-06 一.  概述 该文档详细描述了在Linux环境下安装Kafka和ZooKeeper的全过程,文档中以kafka_2.11-1.1.0.tgz和zookeeper-3.4.12.tar.gz为例. 二.  安装ZooKeeper 2.1  下载ZooKeeper 方式1   http://mirrors.shu.edu.

25.大白话说java并发工具类-CountDownLatch,CyclicBarrier,Semaphore,Exchanger

1. 倒计时器CountDownLatch 在多线程协作完成业务功能时,有时候需要等待其他多个线程完成任务之后,主线程才能继续往下执行业务功能,在这种的业务场景下,通常可以使用Thread类的join方法,让主线程等待被join的线程执行完之后,主线程才能继续往下执行.当然,使用线程间消息通信机制也可以完成.其实,java并发工具类中为我们提供了类似"倒计时"这样的工具类,可以十分方便的完成所说的这种业务场景. 为了能够理解CountDownLatch,举一个很通俗的例子,运动员进行跑

Java 数组工具类排序,最大值最小值等

public class ArrayUtils{ /** * 返回数组最大值 * * @param a * @return */ public static int max(int[] a){ // 返回数组最大值 int x; int aa[]=new int[a.length]; System.arraycopy(a,0,aa,0,a.length); x=aa[0]; for(int i=1;i<aa.length;i++){ if(aa[i]>x){ x=aa[i]; } } retu

java流工具类使用很方便

package com.auto.generate.utils ; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * File Name: StreamTool.jav

java常用工具类(java技术交流群57388149)

package com.itjh.javaUtil; import java.util.ArrayList; import java.util.List; /** * * String工具类. <br> * * @author 宋立君 * @date 2014年06月24日 */ public class StringUtil { private static final int INDEX_NOT_FOUND = -1; private static final String EMPTY =

黑马程序员——Java集合工具类和泛型

Collections工具类和泛型 Collections和Collection Collections和Collection是不同的,Collections是工具类,用来操作集合的,而Collection是集合接口.Collections中有一系列的静态方法用来操作集合,但是不能更改集合内容.比如不能set()不能remove()元素,可以替换全部元素或者添加同一个元素. static List<String> list =Arrays .asList("one Two three

UrlUtils工具类,Java URL工具类,Java URL链接工具类

UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ?Copyright 蕃薯耀 2017年7月15日 http://www.cnblogs.com/fanshuyao/ Java代码   import java.util.Ha

Java日期工具类,Java时间工具类,Java时间格式化

Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ?Copyright  蕃薯耀 2017年2月4日 15:03:27 星期六 http://www.cnblogs.co