用SSLSocketFactory 连接https的地址

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
package com.wtf.demo.socket;
 
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
 
/**
 * Created by wtf on 2015/12/28.
 */
public class HTTPSClient {
 
    public static void main(String[] args) {
        int port = 443;
        String host = "sp0.baidu.com";
 
        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket  = null;
        try {
            socket = (SSLSocket)factory.createSocket(host,port);
 
            //启用密码组
            String[] supportedCipherSuites = socket.getSupportedCipherSuites();
            socket.setEnabledCipherSuites(supportedCipherSuites);
 
            Writer out = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
 
            //https在get中需要完全的URL
            out.write("GET https://" + host + "/ HTTP/1.1\r\n");
            out.write("Host:" + host + "\r\n");
            out.write("\r\n");
            out.flush();
 
 
            //读取相应
 
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 
            //读取首部
            String s;
            while(!(s=reader.readLine()).equals("")){
                System.out.println(s);
            }
            System.out.println();
 
            //读取长度
            String contentLength = reader.readLine();
            int length = Integer.MAX_VALUE;
            try{
                length = Integer.parseInt(contentLength.trim(),16);
            }catch (NumberFormatException e){
               // e.printStackTrace();
                //这个服务器在响应题的第一行没有发送content-length
            }
 
            int c ;
            int i =0 ;
 
            while ((c= reader.read())!=-1 && i++ <length){
                System.out.write(c);
            }
 
            System.out.println();
 
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if(socket!=null){
                  socket.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
 
}

标签: ssl 服务器

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:使用TransitionDrawable实现渐变效果

下一篇: android-cardview简单使用