带jsk证书,请求https接口

首先是三个返回的实体类

BaseVo.java

package https2;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class BaseVo implements Serializable {

	private static final long serialVersionUID = 1L;

	public List<String> getField(Object model) {
		List<String> list = new ArrayList<String>();

		java.lang.reflect.Method[] method = model.getClass().getDeclaredMethods();// 获取对象所有方法
		for (java.lang.reflect.Method m : method) {

			if (m.getName().startsWith("get")) {// 获取get方法
				Object o = null;
				try {
					o = m.invoke(model);
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}// 执行
				if (o == null ) {
					list.add("");
				} else {
					list.add(o.toString());
				}
			}
		}
		return list;
	}
}

  

PageVo.java

package https2;

public class PageVo extends BaseVo {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private int current=1;//当前第几页
	private int currentNum=1;//当前第几页
	private int total;//总数
	private int pages;//页数
	private int number = 15;//每页多少条
	private String column;
	private String order;

	public int getCurrentNum() {
		return currentNum;
	}

	public String getColumn() {
		return column;
	}
	public void setColumn(String column) {
		this.column = column;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public int getCurrent() {
		return current;
	}
	public void setCurrent(int current) {
		this.current = current;
		this.currentNum = current;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
		if(this.total%this.number==0){
			this.pages = this.total / this.number;
		}else{
			this.pages = this.total / this.number + 1;
		}
	}
	public int getPages() {
		return pages;
	}
	public void setPages(int pages) {
		this.pages = pages;
	}

}

  

ResultVo.java

package https2;

public class ResultVo extends BaseVo{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String code;
	private String msg;
	private Object data;
	private PageVo page;

	public PageVo getPage() {
		return page;
	}
	public void setPage(PageVo page) {
		this.page = page;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}

}

  

然后是一个工具类

package https2;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class HostnameVerifierUtil implements HostnameVerifier {

	@Override
	public boolean verify(String hostname, SSLSession arg1) {
		if("localhost".equals(hostname)){
            return true;
        } else {
            return false;
        }
	}

}

  

最后是https请求工具类

package https2;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;  

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import cn.smartercampus.core.vo.ResultVo;

import com.alibaba.fastjson.JSON;

public class HttpsPost {
    /**
     * 获得KeyStore.
     * @param keyStorePath
     *            密钥库路径
     * @param password
     *            密码
     * @return 密钥库
     * @throws Exception
     */
    public static KeyStore getKeyStore(String password, String keyStorePath)
            throws Exception {
        // 实例化密钥库
        KeyStore ks = KeyStore.getInstance("JKS");
        // 获得密钥库文件流
        FileInputStream is = new FileInputStream(keyStorePath);
        // 加载密钥库
        ks.load(is, password.toCharArray());
        // 关闭密钥库文件流
        is.close();
        return ks;
    }  

    /**
     * 获得SSLSocketFactory.
     * @param password
     *            密码
     * @param keyStorePath
     *            密钥库路径
     * @param trustStorePath
     *            信任库路径
     * @return SSLSocketFactory
     * @throws Exception
     */
    public static SSLContext getSSLContext(String password,
            String keyStorePath, String trustStorePath) throws Exception {
        // 实例化密钥库
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        // 获得密钥库
        KeyStore keyStore = getKeyStore(password, keyStorePath);
        // 初始化密钥工厂
        keyManagerFactory.init(keyStore, password.toCharArray());  

        // 实例化信任库
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // 获得信任库
        KeyStore trustStore = getKeyStore(password, trustStorePath);
        // 初始化信任库
        trustManagerFactory.init(trustStore);
        // 实例化SSL上下文
        SSLContext ctx = SSLContext.getInstance("TLS");
        // 初始化SSL上下文
        ctx.init(keyManagerFactory.getKeyManagers(),
                trustManagerFactory.getTrustManagers(), null);
        // 获得SSLSocketFactory
        return ctx;
    }  

    /**
     * 初始化HttpsURLConnection.
     * @param password
     *            密码
     * @param keyStorePath
     *            密钥库路径
     * @param trustStorePath
     *            信任库路径
     * @throws Exception
     */
    public static void initHttpsURLConnection(String password,
            String keyStorePath, String trustStorePath) throws Exception {
        // 声明SSL上下文
        SSLContext sslContext = null;
        // 实例化主机名验证接口
        HostnameVerifierUtil hnv = new HostnameVerifierUtil();
        try {
            sslContext = getSSLContext(password, keyStorePath, trustStorePath);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        if (sslContext != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
                    .getSocketFactory());
        }
        HttpsURLConnection.setDefaultHostnameVerifier(hnv);
    }  

    /**
     * 发送请求.
     * @param httpsUrl
     *            请求的地址
     * @param xmlStr
     *            请求的数据
     */
    public static ResultVo post(String httpsUrl, String xmlStr) {
        HttpsURLConnection urlCon = null;
        try {
            urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
            urlCon.setDoInput(true);
            urlCon.setDoOutput(true);
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Content-Length",
                    String.valueOf(xmlStr.getBytes().length));
            urlCon.setUseCaches(false);  

            urlCon.getOutputStream().write(xmlStr.getBytes("UTF-8"));
            urlCon.getOutputStream().flush();
            urlCon.getOutputStream().close();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlCon.getInputStream()));
            String line;
            StringBuffer resultStr = new StringBuffer();
            while ((line = in.readLine()) != null) {
            	resultStr.append(line);
            }
            System.out.println(resultStr.toString());
            ResultVo resultVo = JSON.parseObject(resultStr.toString(), ResultVo.class);
            return resultVo;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
		return null;
    }  

    /**
     * 测试方法.
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
    	 // 密码
        String password = "";
        // 密钥库
        String keyStorePath = "";
        // 信任库
        String trustStorePath = "";
        // 本地起的https服务
        String httpsUrl = "";
        // 传输文本
        String xmlStr = "";
        HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);
        // 发起请求
        HttpsPost.post(httpsUrl, xmlStr);
    }
}

  

jar 包 fastjson-1.1.27.jar 、log4j-1.2.11.jar

链接:https://pan.baidu.com/s/1UAGUmc7PhUT0Db65YuQMiA
提取码:s70w

原文地址:https://www.cnblogs.com/remember-forget/p/9945628.html

时间: 2024-07-31 07:52:26

带jsk证书,请求https接口的相关文章

php post 请求https接口

/** * POST请求https接口返回内容 * @param string $url [请求的URL地址] * @param string $post [请求的参数] * @return string */ public function post_curls($url, $post) { $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($curl,

PHP Curl请求Https接口

在请求http的时候只需要 file_get_contents("http://www.sojson.com/open/api/weather/json.shtml?city=$Position");就可以了,但是发现这个接口现在变成了https协议了还用这种方法就会403首先看看PHP有没有curl扩展,我是7.2 我用的是Laravel社区的封装好的方法 public static function curl($url, $params = false, $ispost = 0,

cxf webservice请求https

本地java请求https接口,不需要添加证书: 只需要修改配置文件applicationContext-soap-client.xml: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://cxf.apache.org/transports

jmeter压测https接口

jmeter下载完成后cmd进入jmeter\apache-jmeter-5.1.1\bin目录下,执行jmeter.bat,之后进入jmeter GUI页面 1. 创建http授权管理器 其中①:是https接口的url ②.③是登陆https接口登陆账户好密码 ④选择Basic_digest ⑤设置完后点击载入 2. 创建线程组 ①    压测的线程数量 ②   这些线程执行时间 ③   执行这些线程的轮数 3. 在创建的线程组中创建HTTP请求 ①   https接口的话这里一定要写为ht

PHP:CURL分别以GET、POST方式请求HTTPS协议接口api

1.curl以GET方式请求https协议接口 //注意:这里的$url已经包含参数了,不带参数你自己处理哦GET很简单 function curl_get_https($url){ $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1)

curl分别以get,post方式请求https协议接口api

1.curl以GET方式请求https协议接口 //注意:这里的$url已经包含参数了,不带参数你自己处理哦GET很简单 function curl_get_https($url){ $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1)

PHP函数CURL分别以GET、POST方式请求HTTPS协议接口api

1.curl以GET方式请求https协议接口 1 function curl_get_https($url){ 2 $curl = curl_init(); // 启动一个CURL会话 3 curl_setopt($curl, CURLOPT_URL, $url); 4 curl_setopt($curl, CURLOPT_HEADER, 0); 5 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 6 curl_setopt($curl, CURL

AFNetWorking3.0使用 自签名证书的https请求

前几日,项目组出于安全角度的考虑,要求项目中的请求使用https请求,因为是企业内部使用的app,因此使用了自签名的证书,而自签名的证书是不受信任的,所以我们就需要自己来做证书的验证,包括服务器验证客户端的证书和我们要信任服务器的证书,SSL双向认证的原理我这里就不赘述了,这里提供两篇博客 iOS安全系列之一:HTTPS: http://oncenote.com/2014/10/21/Security-1-HTTPS/ iOS安全系列之二:HTTPS进阶: http://oncenote.com

在线HTTP POST/GET模拟请求api接口http请求测试工具https://post.jsonin.com/

在线HTTP POST/GET模拟请求api接口http请求测试工具 在线POST/GET接口测试工具https://post.jsonin.com/ Json在线解析及格式化校验工具 https://jsonin.com/ 原文地址:https://www.cnblogs.com/daxiangxm/p/postjson.html