【Android】OkHttp测试网络连接

    科技2026-08-25  1

    学而不思则罔,思而不学则殆

    【Android】OkHttp测试网络连接

    引言发送网络请求测试http1. 建立socket连接2. 发送请求3. 接受数据测试post数据测试http://www.baidu.com 测试https建立安全通道测试https://www.baidu.com/测试二 总结


    引言

    知道OkHttp底层是通过Socket连接,发送网络请求,本篇文章就是模拟这种方式来发送网路请求

    发送网络请求

    测试http

    1. 建立socket连接

    public static void main(String[] args) { try { testHttp("http://localhost:3434/okhttp"); } catch (IOException e) { e.printStackTrace(); } } private static void testHttp(String url) throws IOException { OkHttpClient client = new OkHttpClient().newBuilder().build(); Request request = new Request.Builder().url(url).build(); System.out.println(request); HttpUrl httpUrl = request.url; System.out.println("httpUrl:" + httpUrl); System.out.println("host:" + httpUrl.host()); System.out.println("port:" + httpUrl.port()); System.out.println("pathSegments:" + httpUrl.pathSegments()); Dns dns = client.dns; System.out.println("dns:" + dns); List<InetAddress> addresses = dns.lookup(httpUrl.host()); //[localhost/127.0.0.1, localhost/0:0:0:0:0:0:0: System.out.println("addresses:" + addresses); SocketFactory socketFactory = client.socketFactory(); System.out.println("SocketFactory:" + socketFactory); //建立安全连接的时候需要 SSLSocketFactory sslSocketFactory = null; HostnameVerifier hostnameVerifier = null; CertificatePinner certificatePinner = null; if (httpUrl.isHttps()) { sslSocketFactory = client.sslSocketFactory(); hostnameVerifier = client.hostnameVerifier(); certificatePinner = client.certificatePinner(); } Authenticator authenticator = client.authenticator(); Proxy proxy = client.proxy(); List<Protocol> protocols = client.protocols; System.out.println("DEFAULT_PROTOCOLS:" + protocols); List<ConnectionSpec> connectionSpecs = client.connectionSpecs; System.out.println("DEFAULT_CONNECTION_SPECS:" + connectionSpecs); ProxySelector proxySelector = ProxySelector.getDefault(); System.out.println("ProxySelector:" + proxySelector); //创建Address Address address = new Address(httpUrl.host, httpUrl.port, dns, socketFactory, sslSocketFactory, hostnameVerifier, certificatePinner, authenticator, proxy, protocols, connectionSpecs, proxySelector); //建立socket连接 Socket socket = socketFactory.createSocket(); //需要IPV4 InetAddress inetAddress = addresses.get(0); //localhost/127.0.0.1 System.out.println(inetAddress); //构建InetSocketAddress InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, httpUrl.port); //localhost/127.0.0.1:3434 System.out.println(inetSocketAddress); //socket.connect(inetAddress, 1000); socket.connect(inetSocketAddress); System.out.println("socket:" + socket); //获取输入输出流 OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); } Request{method=GET, url=http://localhost:3434/okhttp, tag=null} httpUrl:http://localhost:3434/okhttp host:localhost port:3434 pathSegments:[okhttp] dns:okhttp3.Dns$1@7506e922 addresses:[localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] SocketFactory:javax.net.DefaultSocketFactory@4ee285c6 DEFAULT_PROTOCOLS:[h2, http/1.1] DEFAULT_CONNECTION_SPECS:[ConnectionSpec(cipherSuites=[TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA], tlsVersions=[TLS_1_3, TLS_1_2, TLS_1_1, TLS_1_0], supportsTlsExtensions=true), ConnectionSpec()] ProxySelector:sun.net.spi.DefaultProxySelector@621be5d1 localhost/127.0.0.1 localhost/127.0.0.1:3434 socket:Socket[addr=localhost/127.0.0.1,port=3434,localport=58392]

    当目前为止已经建立了连接,由于http是不安全的连接,不需要嵌套安全连接。

    2. 发送请求

    模拟发送http请求

    String header = "GET http://localhost:3434/okhttp HTTP/1.1\r\n"; outputStream.write(header.getBytes()); //发送请求头 outputStream.write("Accept-Encoding: gzip\r\n".getBytes()); outputStream.write("Connection: keep-alive\r\n".getBytes()); outputStream.write("Host: localhost:3434\r\n".getBytes()); outputStream.write("User-Agent: DiyClient/zy\r\n".getBytes()); outputStream.write("\r\n".getBytes()); outputStream.flush();

    3. 接受数据

    //读取数据 byte[] data = new byte[1024]; System.out.println("read..."); int read = inputStream.read(data); while (read != -1) { System.out.println(new String(data)); read = inputStream.read(data); } HTTP/1.1 200 OK Date: Fri, 09 Oct 2020 00:30:45 GMT Content-Type: application/json; charset=UTF-8 author: zy Connection: close Server: Jetty(9.3.2.v20150730) {"code":200,"msg":"OK","data":"GET from Server,Your Msg is :"}

    测试post数据

    确认请求行

    POST http://localhost:3434/okhttp HTTP/1.1 Accept-Encoding: gzip Connection: keep-alive Content-Length: 22 Content-Type: application/json; charset=UTF-8 Host: localhost:3434 User-Agent: zy/test {"name":"zy","age":18}

    用java代码发送:

    //发送请求行 String header = "POST http://localhost:3434/okhttp HTTP/1.1\r\n"; outputStream.write(header.getBytes()); //发送请求头 outputStream.write("Accept-Encoding: gzip\r\n".getBytes()); outputStream.write("Connection: keep-alive\r\n".getBytes()); outputStream.write("Host: localhost:3434\r\n".getBytes()); outputStream.write("Content-Length: 22\r\n".getBytes()); outputStream.write("Content-Type: application/json; charset=UTF-8\r\n".getBytes()); outputStream.write("User-Agent: DiyClient/zy\r\n".getBytes()); outputStream.write("\r\n".getBytes()); outputStream.write("{\"name\":\"zy\",\"age\":18}".getBytes());//发送内容 outputStream.write("\r\n".getBytes()); outputStream.flush();

    结果如下:

    Request{method=GET, url=http://localhost:3434/okhttp, tag=null} httpUrl:http://localhost:3434/okhttp host:localhost port:3434 pathSegments:[okhttp] dns:okhttp3.Dns$1@7506e922 addresses:[localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] SocketFactory:javax.net.DefaultSocketFactory@4ee285c6 DEFAULT_PROTOCOLS:[h2, http/1.1] DEFAULT_CONNECTION_SPECS:[ConnectionSpec(cipherSuites=[TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA], tlsVersions=[TLS_1_3, TLS_1_2, TLS_1_1, TLS_1_0], supportsTlsExtensions=true), ConnectionSpec()] ProxySelector:sun.net.spi.DefaultProxySelector@621be5d1 localhost/127.0.0.1 localhost/127.0.0.1:3434 socket:Socket[addr=localhost/127.0.0.1,port=3434,localport=58505] read... HTTP/1.1 200 OK Date: Fri, 09 Oct 2020 00:46:45 GMT Content-Type: application/json; charset=UTF-8 author: zy Connection: close Server: Jetty(9.3.2.v20150730) {"code":200,"msg":"OK","data":"POST from Server,Your Msg is :{\"name\":\"zy\",\"age\":18}"}

    成功发送post请求。

    测试http://www.baidu.com

    Request{method=GET, url=http://www.baidu.com/, tag=null} httpUrl:http://www.baidu.com/ host:www.baidu.com port:80 pathSegments:[] dns:okhttp3.Dns$1@7506e922 addresses:[www.baidu.com/14.215.177.39, www.baidu.com/14.215.177.38] SocketFactory:javax.net.DefaultSocketFactory@4ee285c6 DEFAULT_PROTOCOLS:[h2, http/1.1] DEFAULT_CONNECTION_SPECS:[ConnectionSpec(cipherSuites=[TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA], tlsVersions=[TLS_1_3, TLS_1_2, TLS_1_1, TLS_1_0], supportsTlsExtensions=true), ConnectionSpec()] ProxySelector:sun.net.spi.DefaultProxySelector@621be5d1 www.baidu.com/14.215.177.39 www.baidu.com/14.215.177.39:80 socket:Socket[addr=www.baidu.com/14.215.177.39,port=80,localport=58439] read... HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=1 Content-Encoding: gzip Content-Length: 3371 Content-Type: text/html Date: Fri, 09 Oct 2020 00:39:35 GMT Etag: "1cd6-5480030886bc0" Expires: Fri, 09 Oct 2020 00:39:36 GMT Last-Modified: Wed, 08 Feb 2017 07:55:35 GMT P3p: CP=" OTI DSP COR IVA OUR IND COM " P3p: CP=" OTI DSP COR IVA OUR IND COM " Server: Apache Set-Cookie: BAIDUID=836C0A6A03607B2CA66A3A8A696F1A79:FG=1; expires=Sat, 09-Oct-21 00:39:35 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1 Set-Cookie: BAIDUID=836C0A6A03607B2C1FD8681AFAB08262:FG=1; expires=Sat, 09-Oct-21 00:39:35 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1 Vary: Accept-Encoding,User-Agent �Y�o���_�\u2Q%�N"� l�i��M���W�Ę_%))��?����)ִ˖�]?Ҵ]��Y�tO�a�4`@;`;^R�d9+:;u��u�����4�ف��L�&��l����͆� �D���$ ��T�Ѱ�4�YbvZ��j�4����y�7}��?���W�����_�����'pAàϢ��u�K�Q+��mPU��������L]���-0�EF�Z��(��v��n�9��� �Ԟ;�h�q��n�Զ�S�^h{0��� �z�\�8}6J�aN������:�V�,~:7��]�F�N-���Q�7̴�˫:|,Ÿ�7?r:�dT���N���S@ed�J���P���X���'Х���S��f�*(GU�j��W�~^� �A��(�~Z?,{T�����Qw����عp_:�[/��4WO"���`�B׋\W�T��֢��Ӭ����+N�����E�r�BF���v�W�&��4I����m�:��4lU��ױ��e�o�����4�����*���ı��:$ �z3u�饉?��îu�GSȵm[� >0�^��a�`2p���Ü?��.Wuġ�q�H�D�쐖�<���:����v�Хu�w��[n`���a��5F���8~8'�����b���OK"�|���N��7L�^��n7����5��0N�H�A�������1clm�z 3xc�h������ Cw�h׵:��:N;;^*Wyp�E}L���= <�SF��h�� o�O4�36���&�A�! bm�T:4��TBX����5l٤���|�ѷ�kTh���и!.c��!��0���ϸl�������y��wF%l6l�ύ�Hf�ہ�� RYc�sW{����-D�80I�N$�B�Tk��ԋ�GC���B���m=��A<QE���+���h��/7Z��?[_��Qi���Z4/�O�7?Je�0���A���+���;9�p1O�yiq>��A����w_���wl6e��R�[GXB�<��G�����18�I>����U��b��� U1o��n`ο? �G����`�!�g�Dnel Q��k�D�S�K$�r(Y. �$���H�{-�I�<�P+��=�c&R�{ �������,j_ ���1a�K��- &4��{rI95���7��{�WcB i6z� � t�3As!s�㱽� ����EH��H���4��ſ�ٮ]4�����ۏ^�r�^鹩�Od �8�NDoy��h��)<�����I�dtiP�- J��}(ݐ&e�"V!���獿;��b���%��� �3~�௨r'��� ��U�1+�A� Q�Ľ�SO���slk��I���X�37H��J�1ڵ�L��3բ�7W+)H�Q�- �k���kꪺ�w8��˅�>X���-e=����e���p�a \eF=f0R�S({P��r�n=[l�X� 0�eN���R_�[��(-./��8����Dž��gq^�Hi�D;���i�>R1��Љഴ�%�S��W �~G�g���s�ya���:���"�7��e�>���K6HW}W�!��^:-o嵭�2ճu�Fں�� \6�P>�߸���Z�����@9�Q���S@$�IΤ�:�ׅd$e�����YL���H����618L1`��{>��Gؑ'�t��N��9�k�OS>�͞c�t��7���~�������/=

    发现返回来的参数都是乱码 原来在请求头中添加了Accept-Encoding字段,但是本地却没有编码处理,所以移除掉这个字段。

    //outputStream.write("Accept-Encoding: gzip\r\n".getBytes());

    把编码屏蔽掉,在测试一下。

    Request{method=GET, url=http://www.baidu.com/, tag=null} httpUrl:http://www.baidu.com/ host:www.baidu.com port:80 pathSegments:[] dns:okhttp3.Dns$1@7506e922 addresses:[www.baidu.com/14.215.177.39, www.baidu.com/14.215.177.38] SocketFactory:javax.net.DefaultSocketFactory@4ee285c6 DEFAULT_PROTOCOLS:[h2, http/1.1] DEFAULT_CONNECTION_SPECS:[ConnectionSpec(cipherSuites=[TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA], tlsVersions=[TLS_1_3, TLS_1_2, TLS_1_1, TLS_1_0], supportsTlsExtensions=true), ConnectionSpec()] ProxySelector:sun.net.spi.DefaultProxySelector@621be5d1 www.baidu.com/14.215.177.39 www.baidu.com/14.215.177.39:80 socket:Socket[addr=www.baidu.com/14.215.177.39,port=80,localport=58461] read... HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=1 Content-Length: 7382 Content-Type: text/html Date: Fri, 09 Oct 2020 00:41:07 GMT Etag: "1cd6-5480030886bc0" Expires: Fri, 09 Oct 2020 00:41:08 GMT Last-Modified: Wed, 08 Feb 2017 07:55:35 GMT P3p: CP=" OTI DSP COR IVA OUR IND COM " P3p: CP=" OTI DSP COR IVA OUR IND COM " Server: Apache Set-Cookie: BAIDUID=BA73D174037EBF3FE9815E4618F7A335:FG=1; expires=Sat, 09-Oct-21 00:41:07 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1 Set-Cookie: BAIDUID=BA73D174037EBF3F53EFF7CAB3C4B594:FG=1; expires=Sat, 09-Oct-21 00:41:07 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1 Vary: Accept-Encoding,User-Agent <!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>�ٶ�һ�£����֪�� </title><style>html{overflow-y:auto}body{font:12px arial;text-align:center;background:#fff}body,p,form,ul{margin:0;padding:0}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:# 00c}a:active{color:#f60}#u{padding:7px 10px 3px 0;text-align:right}#m{width:680px;margin:0 auto}#nv{font-size:16px;margin:0 0 4px;text-align:left;text-indent:117px}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:90px;text-align:left}#kw{width:404px;height:22px;padding:4px 7px;padding:6px 7px 2px\9;font:16px arial;background:url(http://www.baidu.com/img/i-1.0.0.png) no-repeat -304px 0;_background-attachment:fixed;border:1px solid #cdcdcd;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.btn{width:95px;height:32px;padding:0;padding-top:2px\9;border:0;background:#ddd url(http://www.baidu.com/img/i-1.0.0.png) no-repeat;cursor:pointer}.btn_h{background-position:-100px 0}#kw,.btn_wr{margin:0 5px 0 0}.btn_wr{width:97px;height:34px;display:inline-block;background:url(http://www.baidu.com/img/i-1.0.0.png) no-repeat -202px 0;_top:1px;*position:relative}#lk{margin:33px 0}#lk span{font:14px "����"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}#mCon{height:18px;line-height:18px;position:absolu te;right:7px;top:8px;top:10px\9;cursor:pointer;padding:0 18px 0 0;background:url(http://www.baidu.com/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu{width:56px;border:1px solid #9a99ff;list-style:none;position:absolute;right:7px;top:28px;display:none;background:#fff}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none}#mMenu a:hover{background:#d9e1f6}#mMenu .ln{height:1px;background:#ccf;overflow:hidden;margin:2px;font-size:1px;line-height:1px}#cp,#cp a{color:#77c}#sh{display:none;behavior:url(#default#homepage)}</style></head> <body><p id="u"><a href="/gaoji/preferences.html">��������</a>&nbsp;|&nbsp;<a href="http://passport.baidu.com/?login&tpl=mn">��¼</a></p><div id="m"><p id="lg"><img src="http://www.baidu.com/img/baidu_sylogo1.gif" width="270" height="129" usemap="#mp"></p><p id="nv"><a href="http://news.baidu.com">��&nb sp;��</a>��<b>��&nbsp;ҳ</b>��<a href="http://tieba.baidu.com">��&nbsp;��</a>��<a href="http://zhidao.baidu.com">֪&nbsp;��</a>��<a href="http://mp3.baidu.com">MP3</a>��<a href="http://image.baidu.com">ͼ&nbsp;Ƭ</a>��<a href="http://video.baidu.com">��&nbsp;Ƶ</a>��<a href="http://map.baidu.com">��&nbsp;ͼ</a></p><div id="fm"><form name="f" action="/s"><input type="text" name="wd" id="kw" maxlength="100"><input type="hidden" name="rsv_bp" value="0"><span class="btn_wr"><input type="submit" value="�ٶ�һ��" id="su" class="btn" onmousedown="this.className='btn btn_h'" onmouseout="this.className='btn'"></span></form><div id="mCon"><span>���뷨</span></div><ul id="mMenu"><li><a href="#" name="ime_hw">��д</a></li><li><a href="#" name="ime_py">ƴ��</a></li><li class="ln"></li><li><a href="#" name="ime_cl">�ر�</a></li></ul></div> <p id="lk"><a href="http://hi.baidu.com">�ռ�</a>��<a href="http://baike.baidu.com">�ٿ�</a>��<a href="http://www.hao123.com">hao123</a><span> | <a href="/more/">����&gt;&gt;</a></span>< /p><p id="lm"></p><p><a id="sh" onClick="this.setHomePage('http://www.baidu.com/')" href="http://utility.baidu.com/traf/click.php?id=215&url=http://www.baidu.com" onmousedown="return ns_c({'fm':'behs','tab':'homepage','pos':0})">�Ѱٶ���Ϊ��ҳ</a></p><p id="lh"><a href="http://e.baidu.com/?refer=888">����ٶ��ƹ�</a> | <a href="http://top.baidu.com">�������ư�</a> | <a href="http://home.baidu.com">���ڰٶ�</a> | <a href="http://ir.baidu.com">About Baidu</a></p><p id="cp">&copy;2015 Baidu <a href="/duty/">ʹ�ðٶ�ǰ�ض�</a> <a href="http://www.miibeian.gov.cn" target="_blank">��ICP֤030173��</a> <img src="http://gimg.baidu.com/img/gs.gif"></p></div><map name="mp"><area shape="rect" coords="40,25,230,95" href="http://hi.baidu.com/baidu/" target="_blank" title="��˽��� �ٶȵĿռ�" ></map></body> <script>var w=window,d=document,n=navigator,k=d.f.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera,sh=d.getElementById("sh");if(isIE&&sh&&!sh.isHomePage("http:// www.baidu.com/")){sh.style.display="inline"}for(var i=0;i<a.length;i++){a[i].οnclick=function(){if(k.value.length>0){var C=this,A=C.href,B=encodeURIComponent(k.value);if(A.indexOf("q=")!=-1){C.href=A.replace(/q=[^&$]*/,"q="+B)}else{this.href+="?q="+B}}}}(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp.$1)}})();if(n.cookieEnabled&&!/sug?=0/.test(d.cookie)){d.write('<script src=http://www.baidu.com/js/bdsug.js?v=1.0.3.0><\/script>')}function addEV(C,B,A){if(w.attachEvent){C.attachEvent("on"+B,A)}else{if(w.addEventListener){C.addEventListener(B,A,false)}}}function G(A){return d.getElementById(A)}function ns_c(E){var F=encodeURIComponent(window.document.location.href),D="",A="",B="",C=window["BD_PS_C"+(new Date()).getTime()]=new Image();for(v in E){A=E[v];D+=v+"="+A+"&"}B="&mu="+F;C.src="http://nsclick.baidu.com/v.gif?pid=201&pj=www&"+D+"path="+F+"&t="+new Date().getTime();return true}var bdimeHW={hasF:1};var imeTar="kw";var ime_t1=(new Date()).getTime();(function(){var M=G("mCo n"),A=G("mMenu");var B=["���뷨","��д","ƴ��"],O=["cl","hw","py"],D=["","http://www.baidu.com/hw/hwInput_1.1.js","http://www.baidu.com/olime/bdime.js"],N=[0,0,0];var L=n.cookieEnabled;if(L&&/\bbdime=(\d)/.test(d.cookie)){H(O[RegExp.$1],false)}var K=A.getElementsByTagName("a");for(var I=0;I<K.length;I++){K[I].οnclick=F}if(isIE){var E=[];var P=M.getElementsByTagName("*");for(var I=0;I<P.length;I++){E.push(P[I])}E.push(M);var P=A.getElementsByTagName("*");for(var I=0;I<P.length;I++){E.push(P[I])}E.push(A);for(var I=0;I<E.length;I++){E[I].setAttribute("unselectable","on")}}function F(){ime_t1=(new Date()).getTime();var R=this.name.split("_")[1];try{if(w.bdime){bdime.control.closeIme()}}catch(Q){}H(R,true);return false}function H(V,Q){var T=0;if(V==O[1]){T=1;M.innerHTML='<span id="imeS" class="hw">'+B[1]+"</span>";if(isIE){G("imeS").setAttribute("unselectable","on")}function S(){if(!N[1]){if(d.selection&&d.activeElement.id&&d.activeElement.id=="kw"){bdimeHW.hasF=1}bdimeHW.input=imeTar;bdimeHW.submit="su";J(D[1]); setTimeout(function(){if(typeof bdsug!="undefined"){bdsug.sug.initial()}},1000);N[1]=1}else{bdimeHW.reload(Q)}}if(Q){S()}else{addEV(G("imeS"),"click",S)}}else{if(V==O[2]){T=2;M.innerHTML="<span>"+B[2]+"</span>";if(!N[2]){J(D[2]);N[2]=1}else{try{if(w.bdime){bdime.control.openIme()}}catch(U){}}}else{M.innerHTML="<span>"+B[0]+"</span>"}}if(Q&&L){var R=new Date();R.setTime(R.getTime()+365*24*3600*1000);d.cookie="bdime="+T+";domain=baidu.com;path=/;expires="+R.toGMTString()}}function J(Q){if(Q){var R=d.createElement("script");R.src=Q;d.getElementsByTagName("head")[0].appendChild(R)}}function C(R){var R=R||window.event;var Q=R.target||R.srcElement;A.style.display=Q.id=="mCon"&&A.style.display!="block"?"block":"none"}addEV(d,"click",C)})();addEV(w,"load",function(){k.focus()});w.onunload=function(){};;</script> <script type="text/javascript" src="http://www.baidu.com/cache/hps/js/hps-1.1.js"></script> </html>.activeElement.id&&d.activeElement.id=="kw"){bdimeHW.hasF=1}bdimeHW.input=imeTar;bdimeHW.submit="su";J(D[1]);

    测试https

    模拟https的难点在于需要建立一个安全连接后,才能通信。那么怎么才能建立安全连接通道呢?其实OkHttp中已经有了答案,我们先抄一份过来,试着跑跑看。

    建立安全通道

    private static void testHttps(String url) throws IOException { OkHttpClient client = new OkHttpClient().newBuilder().build(); Request request = new Request.Builder().url(url).build(); System.out.println(request); HttpUrl httpUrl = request.url; System.out.println("httpUrl:" + httpUrl); System.out.println("host:" + httpUrl.host()); System.out.println("port:" + httpUrl.port()); System.out.println("pathSegments:" + httpUrl.pathSegments()); Dns dns = client.dns; System.out.println("dns:" + dns); List<InetAddress> addresses = dns.lookup(httpUrl.host()); //[localhost/127.0.0.1, localhost/0:0:0:0:0:0:0: System.out.println("addresses:" + addresses); SocketFactory socketFactory = client.socketFactory(); System.out.println("SocketFactory:" + socketFactory); //建立安全连接的时候需要 SSLSocketFactory sslSocketFactory = null; HostnameVerifier hostnameVerifier = null; CertificatePinner certificatePinner = null; if (httpUrl.isHttps()) { sslSocketFactory = client.sslSocketFactory(); hostnameVerifier = client.hostnameVerifier(); certificatePinner = client.certificatePinner(); } Authenticator authenticator = client.authenticator(); Proxy proxy = client.proxy(); List<Protocol> protocols = client.protocols; System.out.println("DEFAULT_PROTOCOLS:" + protocols); List<ConnectionSpec> connectionSpecs = client.connectionSpecs; System.out.println("DEFAULT_CONNECTION_SPECS:" + connectionSpecs); ProxySelector proxySelector = ProxySelector.getDefault(); System.out.println("ProxySelector:" + proxySelector); //创建Address Address address = new Address(httpUrl.host, httpUrl.port, dns, socketFactory, sslSocketFactory, hostnameVerifier, certificatePinner, authenticator, proxy, protocols, connectionSpecs, proxySelector); //建立socket连接 Socket socket = address.socketFactory.createSocket(); //需要IPV4 InetAddress inetAddress = addresses.get(0); //localhost/127.0.0.1 System.out.println(inetAddress); //构建InetSocketAddress InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, httpUrl.port); //localhost/127.0.0.1:3434 System.out.println(inetSocketAddress); //socket.connect(inetAddress, 1000); socket.connect(inetSocketAddress); System.out.println("socket:" + socket); List<Proxy> proxiesOrNull = address.proxySelector().select(httpUrl.uri()); System.out.println("proxiesOrNull:" + proxiesOrNull); // Create the wrapper over the connected socket. /* autoClose */ //建立安全通道 SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, address.url().host(), address.url().port(), true /* autoClose */); BufferedSource source = Okio.buffer(Okio.source(sslSocket)); BufferedSink sink = Okio.buffer(Okio.sink(sslSocket)); System.out.println("source:" + source); System.out.println("sink:" + sink); //发送请求数据 System.out.println("请求request--------------------------"); //请求行 String requestLine = RequestLine.get(request, proxiesOrNull.get(0).type()); System.out.println(requestLine); sink.writeUtf8(requestLine).writeUtf8("\r\n"); //请求头 String host = "Host: " + httpUrl.host; System.out.println(host); sink.writeUtf8(host).writeUtf8("\r\n"); sink.writeUtf8("\r\n"); //请求正文 //nothing sink.writeUtf8("\r\n"); sink.flush(); //读取数据 byte[] data = new byte[1024]; System.out.println("read..."); int read = source.read(data); System.out.println("read:" + read); System.out.println("响应response--------------------------"); while (read != -1) { System.out.println(new String(data)); read = source.read(data); System.out.println("read:" + read); } }

    其中连接安全通道的是:

    // Create the wrapper over the connected socket. /* autoClose */ SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, address.url().host(), address.url().port(), true /* autoClose */); BufferedSource source = Okio.buffer(Okio.source(sslSocket)); BufferedSink sink = Okio.buffer(Okio.sink(sslSocket)); System.out.println("source:" + source); System.out.println("sink:" + sink);

    有兴趣可以查看:OkHttp源码中RealConnection.connectTls方法中的具体逻辑。RealConnection.java

    测试https://www.baidu.com/

    Request{method=GET, url=https://www.baidu.com/, tag=null} httpUrl:https://www.baidu.com/ host:www.baidu.com port:443 pathSegments:[] dns:okhttp3.Dns$1@7506e922 addresses:[www.baidu.com/14.215.177.38, www.baidu.com/14.215.177.39] SocketFactory:javax.net.DefaultSocketFactory@4ee285c6 DEFAULT_PROTOCOLS:[h2, http/1.1] DEFAULT_CONNECTION_SPECS:[ConnectionSpec(cipherSuites=[TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA], tlsVersions=[TLS_1_3, TLS_1_2, TLS_1_1, TLS_1_0], supportsTlsExtensions=true), ConnectionSpec()] ProxySelector:sun.net.spi.DefaultProxySelector@621be5d1 www.baidu.com/14.215.177.38 www.baidu.com/14.215.177.38:443 socket:Socket[addr=www.baidu.com/14.215.177.38,port=443,localport=59750] proxiesOrNull:[DIRECT] source:buffer(AsyncTimeout.source(source(sun.security.ssl.AppInputStream@6442b0a6))) sink:buffer(AsyncTimeout.sink(sink(sun.security.ssl.AppOutputStream@60f82f98))) 请求request-------------------------- GET / HTTP/1.1 Host: www.baidu.com read... read:1024 响应response-------------------------- HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: no-cache Connection: keep-alive Content-Length: 14722 Content-Type: text/html Date: Sat, 10 Oct 2020 00:02:59 GMT P3p: CP=" OTI DSP COR IVA OUR IND COM " P3p: CP=" OTI DSP COR IVA OUR IND COM " Pragma: no-cache Server: BWS/1.1 Set-Cookie: BAIDUID=2EAFECDDC8AA49589A7317F78D3F24F5:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com Set-Cookie: BIDUPSID=2EAFECDDC8AA49589A7317F78D3F24F5; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com Set-Cookie: PSTM=1602288179; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com Set-Cookie: BAIDUID=2EAFECDDC8AA4958A1B52B5307757E9E:FG=1; max-age=31536000; expires=Sun, 10-Oct-21 00:02:59 GMT; domain=.baidu.com; path=/; version=1; comment=bd Traceid: 160228817902555540587373353520019628821 Vary: Accept-Encoding X-Ua-Compatible: IE=Edge,chrome=1 <!DOCTYPE html><!--STATUS OK--> <html> <head> <meta http-equi read:1024 v="content-type" content="text/html;charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <link rel="dns-prefetch" href="//s1.bdstatic.com"/> <link rel="dns-prefetch" href="//t1.baidu.com"/> <link rel="dns-prefetch" href="//t2.baidu.com"/> <link rel="dns-prefetch" href="//t3.baidu.com"/> <link rel="dns-prefetch" href="//t10.baidu.com"/> <link rel="dns-prefetch" href="//t11.baidu.com"/> <link rel="dns-prefetch" href="//t12.baidu.com"/> <link rel="dns-prefetch" href="//b1.bdstatic.com"/> <title>百度一下,你就知道</title> <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/home/css/index.css" rel="stylesheet" type="text/css" /> <!--[if lte IE 8]><style index="index" >#content{height:480px\9}#m{top:260px\9}</style><![endif]--> <!--[if IE 8]><style index="index" >#u1 a.mnav,#u1 a.mnav:visited{font-family:simsun}</style><![endif]--> <script>var hashMatch = document.location.href.match(/#+(.*wd=[^&].+)/);if (hashMatch && hashMatch[0] && ha read:1024 shMatch[1]) {document.location.replace("http://"+location.host+"/s?"+hashMatch[1]);}var ns_c = function(){};</script> <script>function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('//www.baidu.com/');}</script> <noscript><meta http-equiv="refresh" content="0; url=/baidu.html?from=noscript"/></noscript> <script>window._ASYNC_START=new Date().getTime();</script> </head> <body link="#0000cc"><div id="wrapper" style="display:none;"><div id="u"><a href="//www.baidu.com/gaoji/preferences.html" onmousedown="return user_c({'fm':'set','tab':'setting','login':'0'})">搜索设置</a>|<a id="btop" href="/" onmousedown="return user_c({'fm':'set','tab':'index','login':'0'})">百度首页</a>|<a id="lb" href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" onclick="return false;" onmousedown="return user_c({'fm':'set','tab':'login'})">登录</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" onmousedown="retu read:928 rn user_c({'fm':'set','tab':'reg'})" target="_blank" class="reg">注册</a></div><div id="head"><div class="s_nav"><a href="/" class="s_logo" οnmοusedοwn="return c({'fm':'tab','tab':'logo'})"><img src="//www.baidu.com/img/baidu_jgylogo3.gif" width="117" height="38" border="0" alt="到百度首页" title="到百度首页"></a><div class="s_tab" id="s_tab"><a href="http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'news'})">新闻</a>&#12288;<b>网页</b>&#12288;<a href="http://tieba.baidu.com/f?kw=&fr=wwwt" wdfield="kw" οnmοusedοwn="return c({'fm':'tab','tab':'tieba'})">贴吧</a>&#12288;<a href="http://zhidao.baidu.com/q?ct=17&pn=0&tn=ikaslist&rn=10&word=&fr=wwwt" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'zhidao'})">知道</a>&#12288;<a href="http://music.baidu.com/search?fr=ps&key=" wdfield="key" οnmοusedοwn="return c({'fm':'tab','tab':'musi/passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" οnmοusedοwn="retu read:96 c'})">音乐</a>&#12288;<a href="http://image.baidu.com/i?tn=baiduimage&ps=1&ct=201326592&lm=-1&<div class="s_nav"><a href="/" class="s_logo" οnmοusedοwn="return c({'fm':'tab','tab':'logo'})"><img src="//www.baidu.com/img/baidu_jgylogo3.gif" width="117" height="38" border="0" alt="到百度首页" title="到百度首页"></a><div class="s_tab" id="s_tab"><a href="http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'news'})">新闻</a>&#12288;<b>网页</b>&#12288;<a href="http://tieba.baidu.com/f?kw=&fr=wwwt" wdfield="kw" οnmοusedοwn="return c({'fm':'tab','tab':'tieba'})">贴吧</a>&#12288;<a href="http://zhidao.baidu.com/q?ct=17&pn=0&tn=ikaslist&rn=10&word=&fr=wwwt" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'zhidao'})">知道</a>&#12288;<a href="http://music.baidu.com/search?fr=ps&key=" wdfield="key" οnmοusedοwn="return c({'fm':'tab','tab':'musi/passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" οnmοusedοwn="retu read:1024 cl=2&nc=1&word=" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'pic'})">图片</a>&#12288;<a href="http://v.baidu.com/v?ct=301989888&rn=20&pn=0&db=0&s=25&word=" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'video'})">视频</a>&#12288;<a href="http://map.baidu.com/m?word=&fr=ps01000" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'map'})">地图</a>&#12288;<a href="http://wenku.baidu.com/search?word=&lm=0&od=0" wdfield="word" οnmοusedοwn="return c({'fm':'tab','tab':'wenku'})">文库</a>&#12288;<a href="//www.baidu.com/more/" οnmοusedοwn="return c({'fm':'tab','tab':'more'})">更多»</a></div></div><form id="form" name="f" action="/s" class="fm" ><input type="hidden" name="ie" value="utf-8"><input type="hidden" name="f" value="8"><input type="hidden" name="rsv_bp" value="1"><span class="bg s_ipt_wr"><input name="wd" id="kw" class="s_ipt" value="" maxlength="100"></span><span class="bg s_btn_wr"><input type="submit" id="su" value="百度一下" class="bg s_btn" οnmοusedοwn="this read:1024 .className='bg s_btn s_btn_h'" οnmοuseοut="this.className='bg s_btn'"></span><span class="tools"><span id="mHolder"><div id="mCon"><span>输入法</span></div><ul id="mMenu"><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="javascript:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关闭</a></li></ul></span><span class="shouji"><strong>推荐&nbsp;:&nbsp;</strong><a href="http://w.x.baidu.com/go/mini/8/10000020" οnmοusedοwn="return ns_c({'fm':'behs','tab':'bdbrowser'})">百度浏览器,打开网页快2秒!</a></span></span></form></div><div id="content"><div id="u1"><a href="http://news.baidu.com" name="tj_trnews" class="mnav">新闻</a><a href="http://www.hao123.com" name="tj_trhao123" class="mnav">hao123</a><a href="http://map.baidu.com" name="tj_trmap" class="mnav">地图</a><a href="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a><a href="http://tieba.baidu.com" name="tj_trtieba" class="mnav">贴吧</a><a href="https://passp read:1024 ort.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" id="lb" οnclick="return false;">登录</a><a href="//www.baidu.com/gaoji/preferences.html" name="tj_settingicon" id="pf">设置</a><a href="//www.baidu.com/more/" name="tj_briicon" id="bri">更多产品</a></div><div id="m"><p id="lg"><img src="//www.baidu.com/img/bd_logo.png" width="270" height="129"></p><p id="nv"><a href="http://news.baidu.com">新&nbsp;闻</a> <b>网&nbsp;页</b> <a href="http://tieba.baidu.com">贴&nbsp;吧</a> <a href="http://zhidao.baidu.com">知&nbsp;道</a> <a href="http://music.baidu.com">音&nbsp;乐</a> <a href="http://image.baidu.com">图&nbsp;片</a> <a href="http://v.baidu.com">视&nbsp;频</a> <a href="http://map.baidu.com">地&nbsp;图</a></p><div id="fm"><form id="form1" name="f1" action="/s" class="fm"><span class="bg s_ipt_wr"><input type="text" name="wd" id="kw1" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""> read:928 <input type=hidden name=tn value="baidu"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" value="3"><input type="hidden" name="ie" value="utf-8"><span class="bg s_btn_wr"><input type="submit" value="百度一下" id="su1" class="bg s_btn" onmousedown="this.className='bg s_btn s_btn_h'" onmouseout="this.className='bg s_btn'"></span></form><span class="tools"><span id="mHolder1"><div id="mCon1"><span>输入法</span></div></span></span><ul id="mMenu1"><div class="mMenu1-tip-arrow"><em></em><ins></ins></div><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="javascript:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关闭</a></li></ul></div><p id="lk"><a href="http://baike.baidu.com">百科</a> <a href="http://wenku.baidu.com">文库</a> <a href="http://www.hao123.com">hao123</a><span>&nbsp;|&nbsp;<a href="//www.baidu.com/more/""s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""> read:1024 >更多&gt;&gt;</a></span></p><p id="lm"></p></div></div><div id="ftCon"><div id="ftConw"><p id="lh"><a id="seth" onClick="h(this)" href="/" onmousedown="return ns_c({'fm':'behs','tab':'homepage','pos':0})">把百度设为主页</a><a id="setf" href="//www.baidu.com/cache/sethelp/index.html" onmousedown="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">把百度设为主页</a><a onmousedown="return ns_c({'fm':'behs','tab':'tj_about'})" href="http://home.baidu.com">关于百度</a><a onmousedown="return ns_c({'fm':'behs','tab':'tj_about_en'})" href="http://ir.baidu.com">About Baidu</a></p><p id="cp">&copy;2018&nbsp;Baidu&nbsp;<a href="/duty/" name="tj_duty">使用百度前必读</a>&nbsp;京ICP证030173&nbsp;<img src="http://s1.bdstatic.com/r/www/cache/static/global/img/gs_237f015b.gif"></p></div></div><div id="wrapper_wrapper"></div></div><div class="c-tips-container" id="c-tips-container"></div> <script>window.__async_strategy=2;</script> <script>var bds={se:{},su:{urdata:[],urSend read:1024 Click:function(){}},util:{},use:{},comm : {domain:"http://www.baidu.com",ubsurl : "http://sclick.baidu.com/w.gif",tn:"baidu",queryEnc:"",queryId:"",inter:"",templateName:"baidu",sugHost : "http://suggestion.baidu.com/su",query : "",qid : "",cid : "",sid : "",indexSid : "",stoken : "",serverTime : "",user : "",username : "",loginAction : [],useFavo : "",pinyin : "",favoOn : "",curResultNum:"",rightResultExist:false,protectNum:0,zxlNum:0,pageNum:1,pageSize:10,newindex:0,async:1,maxPreloadThread:5,maxPreloadTimes:10,preloadMouseMoveDistance:5,switchAddMask:false,isDebug:false,ishome : 1},_base64:{domain : "http://b1.bdstatic.com/",b64Exp : -1,pdc : 0}};var name,navigate,al_arr=[];var selfOpen = window.open;eval("var open = selfOpen;");var isIE=navigator.userAgent.indexOf("MSIE")!=-1&&!window.opera;var E = bds.ecom= {};bds.se.mon = {'loadedItems':[],'load':function(){},'srvt':-1};try {bds.se.mon.srvt = parseInt(document.cookie.match(new RegExp("(^| )BDSVRTM=([^;]*)(;|$)"))[2]);document.cookie="BDSVRTM=;expires=Sa read:1024 t, 01 Jan 2000 00:00:00 GMT"; }catch(e){}</script> <script>if(!location.hash.match(/[^a-zA-Z0-9]wd=/)){document.getElementById("ftCon").style.display='block';document.getElementById("u1").style.display='block';document.getElementById("content").style.display='block';document.getElementById("wrapper").style.display='block';setTimeout(function(){try{document.getElementById("kw1").focus();document.getElementById("kw1").parentNode.className += ' iptfocus';}catch(e){}},0);}</script> <script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/jquery/jquery-1.10.2.min_f2fb5194.js"></script> <script>(function(){var index_content = $('#content');var index_foot= $('#ftCon');var index_css= $('head [index]');var index_u= $('#u1');var result_u= $('#u');var wrapper=$("#wrapper");window.index_on=function(){index_css.insertAfter("meta:eq(0)");result_common_css.remove();result_aladdin_css.remove();result_sug_css.remove();index_content.show();index_foot.show();index_u. read:928 show();result_u.hide();wrapper.show();if(bds.su&&bds.su.U&&bds.su.U.homeInit){bds.su.U.homeInit();}setTimeout(function(){try{$('#kw1').get(0).focus();window.sugIndex.start();}catch(e){}},0);if(typeof initIndex=='function'){initIndex();}};window.index_off=function(){index_css.remove();index_content.hide();index_foot.hide();index_u.hide();result_u.show();result_aladdin_css.insertAfter("meta:eq(0)");result_common_css.insertAfter("meta:eq(0)");result_sug_css.insertAfter("meta:eq(0)");wrapper.show();};})();</script> <script>window.__switch_add_mask=1;</script> <script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/global/js/instant_search_newi_redirect1_20bf4036.js"></script> <script>initPreload();$("#u,#u1").delegate("#lb",'click',function(){try{bds.se.login.open();}catch(e){}});if(navigator.cookieEnabled){document.cookie="NOJS=;expires=Sat, 01 Jan 2000 00:00:00 GMT";}</ult_aladdin_css.remove();result_sug_css.remove();index_content.show();index_foot.show();index_u. read:1024 script> <script>$(function(){for(i=0;i<3;i++){u($($('.s_ipt_wr')[i]),$($('.s_ipt')[i]),$($('.s_btn_wr')[i]),$($('.s_btn')[i]));}function u(iptwr,ipt,btnwr,btn){if(iptwr && ipt){iptwr.on('mouseover',function(){iptwr.addClass('ipthover');}).on('mouseout',function(){iptwr.removeClass('ipthover');}).on('click',function(){ipt.focus();});ipt.on('focus',function(){iptwr.addClass('iptfocus');}).on('blur',function(){iptwr.removeClass('iptfocus');}).on('render',function(e){var $s = iptwr.parent().find('.bdsug');var l = $s.find('li').length;if(l>=5){$s.addClass('bdsugbg');}else{$s.removeClass('bdsugbg');}});}if(btnwr && btn){btnwr.on('mouseover',function(){btn.addClass('btnhover');}).on('mouseout',function(){btn.removeClass('btnhover');});}}});</script> <script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/home/js/bri_7f1fa703.js"></script> <script>(function(){var _init=false;window.initIndex=function(){if(_init){return;}_init=true;var w=window,d=document,n=navigator,k=d read:1024 .f1.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera;(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp["\x241"])}})();(function(){var u = G("u1").getElementsByTagName("a"), nv = G("nv").getElementsByTagName("a"), lk = G("lk").getElementsByTagName("a"), un = "";var tj_nv = ["news","tieba","zhidao","mp3","img","video","map"];var tj_lk = ["baike","wenku","hao123","more"];un = bds.comm.user == "" ? "" : bds.comm.user;function _addTJ(obj){addEV(obj, "mousedown", function(e){var e = e || window.event;var target = e.target || e.srcElement;if(target.name){ns_c({'fm':'behs','tab':target.name,'un':encodeURIComponent(un)});}});}for(var i = 0; i < u.length; i++){_addTJ(u[i]);}for(var i = 0; i < nv.length; i++){nv[i].name = 'tj_' + tj_nv[i];}for(var i = 0; i < lk.length; i++){lk[i].name = 'tj_' + tj_lk[i];}})();(function() {var links = {'tj_news': ['word', 'http://news.baidu.com/ns?tn=news&cl=2&rn=20&ct=1&ie=utf-8'],'tj_tieba': ['kw read:1024 ', 'http://tieba.baidu.com/f?ie=utf-8'],'tj_zhidao': ['word', 'http://zhidao.baidu.com/search?pn=0&rn=10&lm=0'],'tj_mp3': ['key', 'http://music.baidu.com/search?fr=ps&ie=utf-8'],'tj_img': ['word', 'http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=&pv=&z=0&ie=utf-8'],'tj_video': ['word', 'http://video.baidu.com/v?ct=301989888&s=25&ie=utf-8'],'tj_map': ['wd', 'http://map.baidu.com/?newmap=1&ie=utf-8&s=s'],'tj_baike': ['word', 'http://baike.baidu.com/search/word?pic=1&sug=1&enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk'),G('cp')],kw = G('kw1');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURICompo read:513 nent('&' + wd + '=' + key) : ( ( url.indexOf('?') > 0 ? '&' : '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {target.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name && ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIComponent(bds.comm.user || '') });};}})();};if(window.pageState==0){initIndex();}})();document.cookie = 'IS_STATIC=1;expires=' + new Date(new Date().getTime() + 10*60*1000).toGMTString();</script> </body></html> enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk'),G('cp')],kw = G('kw1');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURICompo read:28 HTTP/1.1 400 Bad Request ( ( url.indexOf('?') > 0 ? '&' : '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {target.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name && ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIComponent(bds.comm.user || '') });};}})();};if(window.pageState==0){initIndex();}})();document.cookie = 'IS_STATIC=1;expires=' + new Date(new Date().getTime() + 10*60*1000).toGMTString();</script> </body></html> enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk'),G('cp')],kw = G('kw1');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURICompo read:-1

    可以看到正常访问了https的连接

    测试二

    https://blog.csdn.net/yuzhangzhen/article/details/108971902 这是本篇文章的地址。

    Request{method=GET, url=https://blog.csdn.net/yuzhangzhen/article/details/108971902, tag=null} httpUrl:https://blog.csdn.net/yuzhangzhen/article/details/108971902 host:blog.csdn.net port:443 pathSegments:[yuzhangzhen, article, details, 108971902] dns:okhttp3.Dns$1@7506e922 addresses:[blog.csdn.net/112.126.96.31] SocketFactory:javax.net.DefaultSocketFactory@4ee285c6 DEFAULT_PROTOCOLS:[h2, http/1.1] DEFAULT_CONNECTION_SPECS:[ConnectionSpec(cipherSuites=[TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA], tlsVersions=[TLS_1_3, TLS_1_2, TLS_1_1, TLS_1_0], supportsTlsExtensions=true), ConnectionSpec()] ProxySelector:sun.net.spi.DefaultProxySelector@621be5d1 blog.csdn.net/112.126.96.31 blog.csdn.net/112.126.96.31:443 socket:Socket[addr=blog.csdn.net/112.126.96.31,port=443,localport=60159] proxiesOrNull:[DIRECT] source:buffer(AsyncTimeout.source(source(sun.security.ssl.AppInputStream@6442b0a6))) sink:buffer(AsyncTimeout.sink(sink(sun.security.ssl.AppOutputStream@60f82f98))) 请求request-------------------------- GET /yuzhangzhen/article/details/108971902 HTTP/1.1 Host: blog.csdn.net read... read:1024 响应response-------------------------- HTTP/1.1 404 Not Found Server: openresty Date: Sat, 10 Oct 2020 00:11:49 GMT Content-Type: text/html; charset=utf-8 Content-Length: 29999 Connection: keep-alive Keep-Alive: timeout=20 Vary: Accept-Encoding Set-Cookie: dc_sid=72692a321d3fbb58fdc9f7aafe13ea47; Expires=Session; Path=/; Domain=.csdn.net; ETag: "5f6d9ae3-752f" <!DOCTYPE html> <html> <head> <meta name="report" content='{"pid":"404"}'> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="referrer" content="always"> <script src="https://g.csdnimg.cn/??lib/jquery/1.9.1/jquery.js,report/1.5.0/report.js" type="text/javascript"></script> <link rel="stylesheet" href="https://csdnimg.cn/public/static/css/avatar.css"> <meta http-equiv="Cache-Control" content="no-siteapp" /><link rel="alternate" read:1024 media="handheld" href="#" /> <meta name="shenma-site-verification" content="5a59773ab8077d4a62bf469ab966a63b_1497598848"> <title>404</title> <link href="https://csdnimg.cn/public/favicon.ico" rel="SHORTCUT ICON"> <link rel="stylesheet" href="https://g.csdnimg.cn/404error/1.0.0/css/error.css"> <link rel="stylesheet" href="https://g.csdnimg.cn/404error/1.0.0/css/error_e_book.css"> <script src="https://g.csdnimg.cn/fixed-sidebar/1.0.8/fixed-sidebar.js" type="text/javascript"></script> <script type="text/javascript"> ...

    同样也是能够访问https

    总结

    通过上面测试http和https,可以得出网络请求主要是

    建立一个socket通道,当然这个通道分为安全通道和非安全通道;然后获取一个输入流和输出流,输出流把请求信息写入(这个协议也可以自定义,只要通信双方可以规定好)。然后从输出流中获取返回的结果。然后关闭通道,请求结束
    Processed: 0.013, SQL: 9