如何使用HttpURLconnection进行身份验证

时间:2014-04-22 08:57:11

标签: java android authentication httpurlconnection

我试图使用以下代码将网站读作html(即< html>< body> .....< / body>< / html>,但是我需要提供身份验证凭据,我尝试使用java.net.Authenticator提供但它似乎仍然无法工作,(如果我输入www.google.com它可以工作,因为不需要身份验证)(我希望在我的Android应用程序中实现此代码

package com.test.connection;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.HttpURLConnection;

public class Authenticate {

String username="myuser";
String password="mypass";
URL url=null;
String webHtmlData=null;

public static void main(String[] args) {
    Authenticate au=new Authenticate();
    au.setConnectionToWS("https://mysite/New/");      //if i enter www.google.com it works

}

public void setConnectionToWS(String inpUrl){

    Authenticator myAuth = new Authenticator() 
    {
        @Override
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    };

    Authenticator.setDefault(myAuth);

    try {
        url = new URL(inpUrl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();//on debugging the code fails on this line.
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        InputStream in = null;
        try {
            in = new BufferedInputStream(urlConnection.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    finally { 
        webHtmlData=readStream(urlConnection);
        System.out.println(webHtmlData);
        System.out.println("Done!!!");

    }
}

//read data as a browser
private String readStream(HttpURLConnection urlConnection) {

    StringBuffer response = null;

    try {
        BufferedReader is = 
                new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = is.readLine()) != null) {
            response.append(inputLine);
        }
        is.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return response.toString();
}

}

我尝试调试,代码在urlConnection.connect()

行显示以下错误
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
at com.test.connection.Authenticate.setConnectionToWS(Authenticate.java:48)
at com.test.connection.Authenticate.main(Authenticate.java:23)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 19 more

我没有正确提供凭证吗?

将网址传递给www.google.com我将输出显示为

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="/images/google_favicon_128.png" itemprop="image"><title>Google</title><script>(function(){window.google={kEI:"0i1WU93UJMaxrgfQjIDYCw",getEI:function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI},https:function(){return"https:"==window.location.protocol},kEXPI:"17259,4000116,4007661,4007830,4008067,4008133,4008142,4009033,4009352,4009565,4009641,4010806,4010858,4010899,4011228,4011258,4011679,4011959,4012373,4012504,4013374,4013414,4013591,4013723,4013787,4013941,4013967,4013979,4014016,4014431,4014515,4014544,4014636,4014671,4014813,4014991,4015119,4015155,4015197,4015234,4015260,4015342,4015444,4015519,4015550,4015635,4015638,4015639,4015772,4015899,4016004,4016007,4016127,4016293,4016309,4016323,4016361,4016367,4016373,4016425,4016452,4016466,4016479,4016487,4016623,4016639,4016703,4016730,4016767,4016824,4016851,4016855,4016902,4016933,4016952,4016969,4016978,4017041,4017177,4017201,8300015,8300017,8500165,8500223,8500240,8500252,8500283,8500306,8500314,8500332,10200002,10200012,10200029,10200038,10200040,10200044,10200048,10200053,10200055,10200066,10200083,10200120,10200134,10200136,10200155,10200157,10200159,10200163,10200178,10200211,10200221,10200224,10200225,10200236",kCSI:{e:"17259,4000116,4007661,4007830,4008067,4008133,4008142,4009033,4009352,4009565,4009641,4010806,4010858,4010899,4011228,4011258,4011679,4011959,4012373,4012504,4013374,4013414,4013591,4013723,4013787,4013941,4013967,4013979,4014016,4014431,4014515,4014544,4014636,4014671,4014813,4014991,4015119,4015155,4015197,4015234,4015260,4015342,4015444,4015519,4015550,4015635,4015638,4015639,4015772,4015899,4016004,4016007,4016127,4016293,4016309,4016323,4016361,4016367,4016373,4016425,4016452,4016466,4016479,4016487,4016623,4016639,4016703,4016730,4016767,4016824,4016851,4016855,4016902,4016933,4016952,4016969,4016978,4017041,4017177,4017201,8300015,8300017,8500165,8500223,8500240,8500252,8500283,8500306,8500314,8500332,10200002,10200012,10200029,10200038,10200040,10200044,10200048,10200053,10200055,10200066,10200083,10200120,10200134,10200136,10200155,10200157,10200159,10200163,10200178,10200211,10200221,10200224,10200225,10200236",ei:"0i1WU93UJMaxrgfQjIDYCw"},authuser:0,ml:function(){},kHL:"en",time:function(){return(new Date).getTime()},log:function(a,b,c,h,k){var d=new Image,f=google.lc,e=google.li,g="";d.onerror=d.onload=d.onabort=function(){delete f[e]};f[e]=d;c||-1!=b.search("&ei=")||(g="&ei="+google.getEI(h));c=c||"/"+(k||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+g+"&zx="+google.time();a=/^http:/i;a.test(c)&&google.https()?(google.ml(Error("GLMM"),!1,{src:c}),delete f[e]):(d.src=c,google.li=e+1)},lc:[],li:0,y:{},x:function(a,b){google.y[a.id]=[a,b];return!1},load:function(a,b,c){google.x({id:a+l++},function(){google.load(a,b,c)})}};var l=0;})();(function(){google.sn="webhp";google.timers={};google.startTick=function(a,b){var f=google.time();google.timers[a]={t:{start:f},bfr:!!b};};google.tick=function(a,b,f){google.timers[a]||google.startTick(a);google.timers[a].t[b]=f||google.time()};google.startTick("load",!0);try{}catch(d){}})();var _gjwl=location;function _gjuc(){var a=_gjwl.href.indexOf("#");if(0<=a&&(a=_gjwl.href.substring(a),0<a.indexOf("&q=")||0<=a.indexOf("#q="))&&(a=a.substring(1),-1==a.indexOf("#"))){for(var d=0;d<a.length;){var b=d;"&"==a.charAt(b)&&++b;var c=a.indexOf("&",b);-1==c&&(c=a.length);b=a.substring(b,c);if(0==b.indexOf("fp="))a=a.substring(0,d)+a.substring(c,a.length),c=d;else if("cad=h"==b)return 0;d=c}_gjwl.href="/search?"+a+"&cad=h";return 1}return 0}function _gjh(){!_gjuc()&&window.google&&google.x&&google.x({id:"GJH"},function(){google.nav&&google.nav.gjh&&google.nav.gjh()})};window._gjh&&_gjh();</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#36c}.q{color:#00c}.ts td{padding:0}.ts{border-collapse:collapse}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}a.gb1,a.gb2,a.gb3,a.gb4{color:#11c !important}body{background:#fff;color:black}a{color:#11c;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#36c}a:visited{color:#551a8b}a.gb1,a.gb4{text-decoration:underline}a.gb3:hover{text-decoration:none}#ghead a.gb2:hover{color:#fff !important}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#eee;border:solid 1px;border-color:#ccc #999 #999 #ccc;height:30px}.lsbb{display:block}.ftl,#fll a{display:inline-block;margin:0 12px}.lsb{background:url(/images/srpr/nav_logo80.png) 0 -258px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#ccc}.lst:focus{outline:none}#addlang a{padding:0 3px}</style><script></script></head><body bgcolor="#fff"><script>(function(){var src='/images/nav_logo176.png';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}if (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}}})();</script><textarea id="csi" style="display:none"></textarea><div id="mngb"> <div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="https://www.google.co.in/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="https://maps.google.co.in/maps?hl=en&tab=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href="https://www.youtube.com/?gl=IN&tab=w1">YouTube</a> <a class=gb1 href="https://news.google.co.in/nwshp?hl=en&tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="http://www.google.co.in/intl/en/options/"><u>More</u> &raquo;</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.co.in/history/optout?hl=en" class=gb4>Web History</a> | <a  href="/preferences?hl=en" class=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en&continue=https://www.google.co.in/" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div>  </div><center><br clear="all" id="lgpd"><div id="lga"><a href="/search?site=&amp;ie=UTF-8&amp;q=Earth+Day&amp;oi=ddle&amp;ct=earth-day-5158363801321472&amp;hl=en"><img alt="Earth Day 2014" border="0" height="170" src="/logos/doodles/2014/earth-day-5158363801321472.3-hp.jpg" title="Earth Day 2014" width="400" id="hplogo" onload="window.lol&&lol()"><br></a><br></div><form action="/search" name="f"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%">&nbsp;</td><td align="center" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en-IN" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><div class="ds" style="height:32px;margin:4px 0"><input style="color:#000;margin:0;padding:5px 8px 0 6px;vertical-align:top" autocomplete="off" class="lst" value="" title="Google Search" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class="lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class="ds"><span class="lsbb"><input class="lsb" value="I'm Feeling Lucky" name="btnI" onclick="if(this.form.q.value)this.checked=1; else top.location='/doodles/'" type="submit"></span></span></td><td class="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en-IN&amp;authuser=0">Advanced search</a><a href="/language_tools?hl=en-IN&amp;authuser=0">Language tools</a></td></tr></table><input id="gbv" name="gbv" type="hidden" value="1"></form><div id="gac_scont"></div><div style="font-size:83%;min-height:3.5em"><br><div id="prm"><font id="hpplink" size="-1" style="behavior:url(#default#userdata);display:none"><span style="color:red"></span>There's no place like <a href="https://mybeautifulearth.withgoogle.com/" onclick="google.promos&&google.promos.link&& google.promos.link.cl()">#MyBeautifulEarth</a>. Share your photos for Earth Day.</font><br><br><br><script type="text/javascript">(function(){var e={ACCEPT:"a",LIMITED_ACCEPT:"l",CANCEL:"c",DISMISS:"d",CLICK:"h",IMPRESSION:"i",NO_THANKS:"n",X_BUTTON:"x",MGMHP_ACCEPT:"ma",MGMHP_CANCEL:"mc",MGMHP_IMPRESSION:"mi",MGMHPPD_ACCEPT:"pa",MGMHPPD_CANCEL:"pc",MGMHPPD_IMPRESSION:"pi",MGMHPPD_NO_THANKS:"pn",MGMHPPD_NO_BUTTON:"px",MGMHPPD_DISMISS:"pd",PUSHDOWN_ACCEPT:"gpa",PUSHDOWN_IMPRESSION:"gpi",PUSHDOWN_NO_THANKS:"gpn",PUSHDOWN_X_BUTTON:"gpx",PUSHDOWN_DISMISS:"gpd"};var f,g,h=0,k;google.promos=google.promos||{};google.promos.link=google.promos.link||{};google.promos.link.getExtraLogData_=function(b){var a=document.getElementById(k);if(a){var c=g+"_upccb",d=parseInt(window.gbar.up.gpd(a,c)||0,10);d++;h++;window.gbar.up.spd(a,c,d);a=[["upcc",h].join("="),["upccb",d].join("=")];b&&a.push(b);return a.join("&")}};google.promos.link.cl=function(b){try{window.gbar.up.sl(g,f,e.CLICK,google.promos.link.getExtraLogData_(b),1)}catch(a){google.ml(a,!1,{cause:f+"_CL"})}};function l(){var b=["gpd","spd","sl"];if(!window.gbar||!window.gbar.up)return!1;for(var a=0,c;c=b[a];a++)if(!(c in window.gbar.up))return!1;return!0}google.promos.link.init=function(b,a,c){try{if(l()){g=b;f=a;k=c;var d=document.getElementById(k);d&&(d.style.display="",window.gbar.up.sl(g,f,e.IMPRESSION))}else google.ml(Error("apa"),!1,{cause:a+"_INIT"})}catch(m){google.ml(m,!1,{cause:f+"_INIT"})}};})();</script><script>(function(){var sourceWebappPromoID=5076958;var payloadType=3;window.gbar&&gbar.up&&gbar.up.r&&gbar.up.r(payloadType,function(show){if (show){google.promos.link.init(sourceWebappPromoID,payloadType,'hpplink');}});})();</script></div><div id=als><font size=-1 id=addlang>Google.co.in offered in: <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=hi&amp;source=homepage">Hindi</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=bn&amp;source=homepage">Bengali</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=te&amp;source=homepage">Telugu</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=mr&amp;source=homepage">Marathi</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=ta&amp;source=homepage">Tamil</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=gu&amp;source=homepage">Gujarati</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=kn&amp;source=homepage">Kannada</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=ml&amp;source=homepage">Malayalam</a> <a href="https://www.google.co.in/setprefs?sig=0_EepL_l4qMit4OlqjH-8hw4BXYzY%3D&amp;hl=pa&amp;source=homepage">Punjabi</a></font><br><br></div></div><span id="footer"><div style="font-size:10pt"><div style="margin:19px auto;text-align:center" id="fll"><a href="/intl/en/ads/">Advertising&nbsp;Programs</a><a href="http://www.google.co.in/services/">Business Solutions</a><a href="https://plus.google.com/104205742743787718296" rel="publisher">+Google</a><a href="/intl/en/about.html">About Google</a><a href="https://www.google.co.in/setprefdomain?prefdom=US&amp;sig=0_a3KhXY95e1JckKNc639UUxpoH1s%3D" id="fehl">Google.com</a></div></div><p style="color:#767676;font-size:8pt">&copy; 2013 - <a href="/intl/en/policies/">Privacy & Terms</a></p></span></center><div id=xjsd></div><div id=xjsi data-jiis="bp"><script>if(google.y)google.y.first=[];(function(){function b(a){window.setTimeout(function(){var c=document.createElement("script");c.src=a;document.getElementById("xjsd").appendChild(c)},0)}google.dljp=function(a){google.xjsu=a;b(a)};google.dlj=b;})();if(!google.xjs){window._=window._||{};window._._DumpException=function(e){throw e};if(google.timers&&google.timers.load.t){google.timers.load.t.xjsls=new Date().getTime();}google.dljp('/xjs/_/js/k\x3dxjs.hp.en_US.BAKw5TDNxgo.O/m\x3dsb_he,pcc/rt\x3dj/d\x3d1/sv\x3d1/rs\x3dAItRSTObSXX9tFFoWD5P-r2jGfYxGR8kqw');google.xjs=1;}google.pmc={"sb_he":{"agen":true,"cgen":true,"client":"heirloom-hp","dh":true,"ds":"","eqch":true,"fl":true,"host":"google.co.in","jam":0,"jsonp":true,"msgs":{"cibl":"Clear Search","dym":"Did you mean:","lcky":"I\u0026#39;m Feeling Lucky","lml":"Learn more","oskt":"Input tools","psrc":"This search was removed from your \u003Ca href=\"/history\"\u003EWeb History\u003C/a\u003E","psrl":"Remove","sbit":"Search by image","srch":"Google Search"},"ovr":{},"pq":"","qcpw":false,"scd":10,"sce":5,"stok":"Ku9ucJmRzgiX52a-aokAZPKe2bE"},"pcc":{}};google.y.first.push(function(){if(google.med){google.med('init');google.initHistory();google.med('history');}});if(google.j&&google.j.en&&google.j.xi){window.setTimeout(google.j.xi,0);}</script></div><script>(function(){if(google.timers&&google.timers.load.t){var b,c,d,e,g=function(a,f){a.removeEventListener?(a.removeEventListener("load",f,!1),a.removeEventListener("error",f,!1)):(a.detachEvent("onload",f),a.detachEvent("onerror",f))},h=function(a){e=(new Date).getTime();++c;a=a||window.event;a=a.target||a.srcElement;g(a,h)},k=document.getElementsByTagName("img");b=k.length;for(var l=c=0,m;l<b;++l)m=k[l],m.complete||"string"!=typeof m.src||!m.src?++c:m.addEventListener?(m.addEventListener("load",h,!1),m.addEventListener("error",h,!1)):(m.attachEvent("onload",h),m.attachEvent("onerror",h));d=b-c;var n=function(){if(google.timers.load.t){google.timers.load.t.ol=(new Date).getTime();google.timers.load.t.iml=e;google.kCSI.imc=c;google.kCSI.imn=b;google.kCSI.imp=d;void 0!==google.stt&&(google.kCSI.stt=google.stt);google.csiReport&&google.csiReport()}};window.addEventListener?window.addEventListener("load",n,!1):window.attachEvent&&window.attachEvent("onload",n);google.timers.load.t.prt=e=(new Date).getTime()};})();</script></body></html>
Done!!!

我需要在传递需要身份验证的网址时获得相同的结果(在浏览器上输入我的网址时会显示一个弹出窗口,输入用户名和密码,提交后我将被定向到页面)

1 个答案:

答案 0 :(得分:1)

如果您有自签名证书,则应将自签名证书导入java信任库或以简单方式添加以下代码以绕过证书验证。在生产中,最好使用可信证书。

Authenticator.setDefault(myAuth); 行之后添加以下代码。

// Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    }
    };

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    try {
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

最后改变这一行

urlConnection = (HttpURLConnection) url.openConnection();

to(使用HttpsUrlConnection)

urlConnection = (HttpsURLConnection) url.openConnection();