在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

用SSLSocketFactory 连接https的地址

2016-12-20 13:15| 发布者: zhangjf| 查看: 443| 评论: 0

摘要: 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 v ...
  1. package com.wtf.demo.socket;
  2. import javax.net.ssl.SSLSocket;
  3. import javax.net.ssl.SSLSocketFactory;
  4. import java.io.*;
  5. /**
  6. * Created by wtf on 2015/12/28.
  7. */
  8. public class HTTPSClient {
  9. public static void main(String[] args) {
  10. int port = 443;
  11. String host = "sp0.baidu.com";
  12. SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  13. SSLSocket socket = null;
  14. try {
  15. socket = (SSLSocket)factory.createSocket(host,port);
  16. //启用密码组
  17. String[] supportedCipherSuites = socket.getSupportedCipherSuites();
  18. socket.setEnabledCipherSuites(supportedCipherSuites);
  19. Writer out = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
  20. //https在get中需要完全的URL
  21. out.write("GET https://" + host + "/ HTTP/1.1rn");
  22. out.write("Host:" + host + "rn");
  23. out.write("rn");
  24. out.flush();
  25. //读取相应
  26. BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  27. //读取首部
  28. String s;
  29. while(!(s=reader.readLine()).equals("")){
  30. System.out.println(s);
  31. }
  32. System.out.println();
  33. //读取长度
  34. String contentLength = reader.readLine();
  35. int length = Integer.MAX_VALUE;
  36. try{
  37. length = Integer.parseInt(contentLength.trim(),16);
  38. }catch (NumberFormatException e){
  39. // e.printStackTrace();
  40. //这个服务器在响应题的第一行没有发送content-length
  41. }
  42. int c ;
  43. int i =0 ;
  44. while ((c= reader.read())!=-1 && i++ <length){
  45. System.out.write(c);
  46. }
  47. System.out.println();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }finally {
  51. try{
  52. if(socket!=null){
  53. socket.close();
  54. }
  55. }catch (Exception e){
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 12:38

Copyright 2015-2025 djqfx

返回顶部