public static SSLConnectionSocketFactory getSSLSocktetBidirectional() throws Exception {
SSLConnectionSocketFactory sslsf = null;
try{
// CA certificate is used to authenticate server
String linuxLocalIp = IpDataUtils.getSelfPublicIp();
//正式环境代码,配置正常逻辑代码
CertificateFactory cAf = CertificateFactory.getInstance("X.509");
FileInputStream caIn = new FileInputStream(CA_PATH);
X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
KeyStore caKs = KeyStore.getInstance("JKS");
caKs.load(null, null);
//caKs.setCertificateEntry("ca-certificate", ca);
caKs.setCertificateEntry("verify", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(caKs);
// client key and certificates are sent to server so it can authenticate us
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream crtIn = new FileInputStream(CRT_PATH);
X509Certificate caCert = (X509Certificate) cf.generateCertificate(crtIn);
crtIn.close();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry("certificate", caCert);
ks.setKeyEntry("private-key", getPrivateKey(KEY_PATH), PASSWORD.toCharArray(), new java.security.cert.Certificate[] { caCert });
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(ks, PASSWORD.toCharArray());
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
sslsf = new SSLConnectionSocketFactory(context,null, null,NoopHostnameVerifier.INSTANCE);
}catch (Exception e){
System.out.println("证书加载失败");
e.printStackTrace();
}
return sslsf;
}
private static PrivateKey getPrivateKey(String path) throws Exception {
//byte[] buffer = Base64.getDecoder().decode(getPem(path));
// Base64 base64 = new Base64();
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(getPem(path));
BASE64Decoder decoder = new BASE64Decoder();
//byte[] buffer = decoder.decodeBuffer(getPem(path));
//PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(getPem(path)));
/* PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;*/
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
}
private static String getPem(String path) throws Exception {
FileInputStream fin = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
fin.close();
return sb.toString();
}
以上没什么就直接帖代码就行
接下来
public static String CA_PATH = "C:/Users/lsy/Desktop/certs/ca.crt";
public static String CRT_PATH = "C:/Users/lsy/Desktop/certs/client.crt";
public static String KEY_PATH = "C:/Users/lsy/Desktop/certs/client.key";
public static String PASSWORD = "lisenyuan";
public static String httpPost( List<shengxinFileDataVm> list) throws IOException {
CloseableHttpClient httpClient = null;
List<ShengxinDataAdd> listData=new ArrayList();
JSONObject jsonObject = new JSONObject();
/* Map map=new HashMap<>();*/
ShengxinDataAdd shengxindataadd=new ShengxinDataAdd();
StringBuffer sb1=new StringBuffer();
StringBuffer sb2=new StringBuffer();
String linuxLocalIp = IpDataUtils.getSelfPublicIp();
String igIp=null;
for (int i = 0; i < list.size(); i++) {
ShengxinFileData shengxinFileData1 = list.get(i);
sb1.append(shengxinFileData1.getSequencingNumber());
sb1.append(",");
sb2.append(shengxinFileData1.getSpecimenName());
sb2.append(",");
}
shengxindataadd.setSequencingNumber(sb1.substring(0,sb1.length()-1));
shengxindataadd.setSpecimenName(sb2.substring(0,sb2.length()-1));
shengxindataadd.setTaskId(list.get(0).getTaskId().toString());
shengxindataadd.setProjectNumber(list.get(0).getProjectNumber());
shengxindataadd.setPanelNumber(list.get(0).getPanel());
shengxindataadd.setFileType(list.get(0).getFileType());
shengxindataadd.setContractNumber(list.get(0).getContractNumber());
shengxindataadd.setCallback(igIp);
String stringJSON = JSON.toJSONString(shengxindataadd);
String result = null;
// System.out.println("请求数据:"+jsonObject.toJSONString());
System.out.println("请求数据:"+stringJSON);
try{
SSLConnectionSocketFactory sslsf = getSSLSocktetBidirectional();
//设置认证信息到httpclient
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
}catch (Exception e){
System.out.println("证书读取失败");
e.printStackTrace();
return "证书读取失败";
}
// 根据默认超时限制初始化requestConfig
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(25000).setConnectTimeout(25000).build();
//post通讯初始化
HttpPost httpPost = new HttpPost("https:");
// 设置报文头 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
/* httpPost.addHeader("igIp", igIp);*/
//添加请求报文体
StringEntity reqentity = new StringEntity(stringJSON, "UTF-8");
httpPost.setEntity(reqentity);
// 设置请求器的配置
httpPost.setConfig(requestConfig);
try {
CloseableHttpResponse response = null;
InputStream reqin = null;
try {
//打印请求报文体
reqin = httpPost.getEntity().getContent();
String reqBbody = StreamUtils.copyToString(reqin, StandardCharsets.UTF_8);
System.out.println("请求数据:"+reqBbody);
//与服务端通讯
response = httpClient.execute(httpPost);
//打印通讯状态
System.out.println(JSONObject.toJSONString(response.getStatusLine()));
JSONObject.toJSONString(response.getStatusLine());
HttpEntity entity = response.getEntity();
InputStream in = null;
try {
in = entity.getContent();
String rspBbody = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
System.out.println("应答为:"+rspBbody);
in.close();
if(response.getStatusLine().getStatusCode()==200){
result="成功";
}else{
result="失敗";
}
// result = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
System.out.println("服务端应答信息读取失败");
e.printStackTrace();
return "服务端应答信息读取失败";
}finally {
if (in !=null){
in.close();
}
}
} catch (IOException e) {
System.out.println("与服务端通讯失败");
e.printStackTrace();
return "与服务端通讯失败";
}finally {
try{
//释放资源
if (httpClient != null){
httpClient.close();
}
if (response != null){
response.close();
}
if (reqin != null){
reqin.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
} finally {
httpPost.abort();
}
return result;
}
重要的来了,有人不知道哪里lisenyuan 这个字符串是怎么来的
keytool -import -alias mycert -keystore cacerts -file C:/Users/lsy/Desktop/certs/ca.crt
执行上面命令设置就行了