资讯专栏INFORMATION COLUMN

java必知必会之SecureSocket

kidsamong / 2769人阅读

SSL,Secure Sockets Layer,安全Socket层
TLS,Transport Layer Security,传输层安全协议

package network.secure;
import java.io.*;
import javax.net.ssl.*;
public class HTTPSClient {
    
  public static void main(String[] args) {
    
    if (args.length == 0) {
      System.out.println("Usage: java HTTPSClient2 host");
      return;
    }       
    
    int port = 443; // default https port
    String host = args[0];
    
    SSLSocketFactory factory 
        = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = null;
    try {         
      socket = (SSLSocket) factory.createSocket(host, port);
      // enable all the suites
      String[] supported = socket.getSupportedCipherSuites();
      socket.setEnabledCipherSuites(supported);
      Writer out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
      // https requires the full URL in the GET line
      out.write("GET http://" + host + "/ HTTP/1.1
");
      out.write("Host: " + host + "
");
      out.write("
");
      out.flush(); 
      
      // read response
      BufferedReader in = new BufferedReader(
          new InputStreamReader(socket.getInputStream()));
      
      // read the header
      String s;
      while (!(s = in.readLine()).equals("")) {
        System.out.println(s);
      }
      System.out.println();
      
      // read the length
      String contentLength = in.readLine();
      int length = Integer.MAX_VALUE;
      try {
        length = Integer.parseInt(contentLength.trim(), 16);
      } catch (NumberFormatException ex) {
        // This server doesn"t send the content-length
        // in the first line of the response body
      }
      System.out.println(contentLength);
      
      int c;
      int i = 0;
      while ((c = in.read()) != -1 && i++ < length) {
        System.out.write(c);
      }
      
      System.out.println();
    } catch (IOException ex) {
      System.err.println(ex);
    } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {}
    }
  }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65957.html

相关文章

  • java必知会之ServerSocket

    摘要:单个请求范围之外的异常可能会关闭服务器。客户端可能超时或崩溃,用户可能取消事务,网络可能在流量高峰期间瘫痪,黑客可能发动拒绝服务攻击。如果默认长度不够大,一些的构造函数还允许改变这个队列的长度,不能不能超过操作系统支持的最大值。 ServerSocket的生命周期 一个ServerSocket的基本生命周期:1)使用一个ServerSocket构造函数在一个特定端口创建一个新的Serv...

    chinafgj 评论0 收藏0
  • Java必知会之socket

    摘要:上,数据按有限大小的包传输,这些包成为数据报,每个数据报包含一个首部和一个有效载荷。不过,由于数据报长度有限,通常必须将数据分解为多个包,再在目的地重新组合。这两个构造函数,在返回之前会与远程主机建立一个活动的网络连接。 Internet上,数据按有限大小的包传输,这些包成为数据报(datagram),每个数据报包含一个首部(header)和一个有效载荷(payload)。首部包含包发...

    jackzou 评论0 收藏0

发表评论

0条评论

kidsamong

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<