码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-11-19 14:03:38      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:oct   服务器   sort   throws   type   href   factor   set   read   

原文: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请求

标签:oct   服务器   sort   throws   type   href   factor   set   read   

原文地址:https://www.cnblogs.com/xzp0222/p/11888694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!