通过JDK自带的HttpURLConnection发送HTTPS请求

Posted xzp0222

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过JDK自带的HttpURLConnection发送HTTPS请求相关的知识,希望对你有一定的参考价值。

原文:https://www.cnblogs.com/deityjian/p/11426677.html#top

import java.security.cert.CertificateException;  
import java.security.cert.X509Certificate;  
import javax.net.ssl.X509TrustManager;  
  
public class MyX509TrustManager implements X509TrustManager {  
  
    @Override  
    public void checkClientTrusted(X509Certificate[] chain, String authType)  
            throws CertificateException {  
        // TODO Auto-generated method stub  
  
    }  
  
    @Override  
    public void checkServerTrusted(X509Certificate[] chain, String authType)  
            throws CertificateException {  
        // TODO Auto-generated method stub  
  
    }  
  
    @Override  
    public X509Certificate[] getAcceptedIssuers() {  
        // TODO Auto-generated method stub  
        return null;  
    }  
  
}

注意:

1)需要的包都是java自带的,所以不用引入额外的包。

2.)可以看到里面的方法都是空的,当方法为空是默认为所有的链接都为安全,也就是所有的链接都能够访问到。当然这样有一定的安全风险,可以根据实际需要写入内容。

2。编写http请求方法

/* 
 * 处理https GET/POST请求 
 * 请求地址、请求方法、参数 
 * */  
public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){  
    StringBuffer buffer=null;  
    try{  
    //创建SSLContext  
    SSLContext sslContext=SSLContext.getInstance("SSL");  
    TrustManager[] tm={new MyX509TrustManager()};  
    //初始化  
    sslContext.init(null, tm, new java.security.SecureRandom());;  
    //获取SSLSocketFactory对象  
    SSLSocketFactory ssf=sslContext.getSocketFactory();  
    URL url=new URL(requestUrl);  
    HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();  
    conn.setDoOutput(true);  
    conn.setDoInput(true);  
    conn.setUseCaches(false);  
    conn.setRequestMethod(requestMethod);  
    //设置当前实例使用的SSLSoctetFactory  
    conn.setSSLSocketFactory(ssf);  
    conn.connect();  
    //往服务器端写内容  
    if(null!=outputStr){  
        OutputStream os=conn.getOutputStream();  
        os.write(outputStr.getBytes("utf-8"));  
        os.close();  
    }  
      
    //读取服务器端返回的内容  
    InputStream is=conn.getInputStream();  
    InputStreamReader isr=new InputStreamReader(is,"utf-8");  
    BufferedReader br=new BufferedReader(isr);  
    buffer=new StringBuffer();  
    String line=null;  
    while((line=br.readLine())!=null){  
        buffer.append(line);  
    }  
    }catch(Exception e){  
        e.printStackTrace();  
    }  
    return buffer.toString();  
}

可见和http访问的方法类似,只是多了SSL的相关处理。

3。测试

 public static void main(String[] args){  
     String s=httpsRequest("https://kyfw.12306.cn/","GET",null);  
     System.out.println(s);  
 } 

https的链接一定要进行SSL的验证或者过滤之后才能够访问。

项目应用:

package com.jd.ofc.trace.web.controller;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
 * 证书信任管理器(用于https请求)
 * */
public class MyX509TrustManager1 implements 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 new X509Certificate[0];
    }


    /*
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     * */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        StringBuffer buffer=null;
        try{
            //创建SSLContext
            SSLContext sslContext=SSLContext.getInstance("SSL");
            TrustManager[] tm={new MyX509TrustManager1()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url=new URL(requestUrl);
            HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();

            String cookies="__jdv=XXX";

            conn.setRequestProperty("Authorization","Basic XXX");
            conn.setRequestProperty("cookie",cookies);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);

            conn.connect();
            //往服务器端写内容
            if(null!=outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is=conn.getInputStream();
            InputStreamReader isr=new InputStreamReader(is,"utf-8");
            BufferedReader br=new BufferedReader(isr);
            buffer=new StringBuffer();
            String line=null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
       }
       
       public static void main(String[] args){
           String s=httpsRequest("https://xx.xx.com/v3/clusters?limit=-1&sort=name","GET",null);
           System.out.println(s);
       }
    }

 

以上是关于通过JDK自带的HttpURLConnection发送HTTPS请求的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient系列,JDK HttpURLConnection

Open Feign 超时 Ribbon 超时 相关内容

两个java项目之间的通讯

JDK原生的HttpURLConnection请求实例

REST访问(RestTemplate)

HttpURLConnection与HttpClient区别及联系