用SSLSocketFactory 連接https的地址

碼頭工人 8年前發布 | 3K 次閱讀 Java

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();
        }
    }
}

}</pre>

 本文由用戶 admin 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!