天天看點

httpclient.execute()不執行也不報錯解決辦法

當然,這裡隻是根據我的錯誤具體說一下解決辦法,情況與我有不同的愛莫能助了。

public List<String> getUsernameFromHtml()
        { 
            List<String> list=null;
            HttpGet hg=new HttpGet("http://www.sina.com/PUB/foot.aspx");
            try {
                hg.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36" );
                hg.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                hg.setHeader( "Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
                hg.setConfig(requestConfig); //設定逾時

                CloseableHttpResponse response=httpclient.execute(hg);
                System.out.println(response.getStatusLine()); 
                HttpEntity entity=response.getEntity();
                HtmlUtils hu=new HtmlUtils();
                list=hu.getHtmlContentsByidName(EntityUtils.toString(entity), "lbl_userinfo");
                //這一串字元還需要用htmlparse進行解析哦
            }catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
           

這段代碼其實是沒有任何問題的,所有的變量我都調試過,都有值,

但是就是執行到httpclient.execute()的時候就是不執行,我猜想是不是因為httpclient執行個體已經沒有了,是不是已經被java的回收器回收了。

于是我就從新new 了一個,放了進去,将原來的cookie也放進去,就可以做到同一個cookie通路了

修改後添加代碼為

CloseableHttpClient httpclient2 = HttpClients.custom()
                        .setDefaultCookieStore(cos)
                        .build();  
           

——-後之覽者,或将有感于斯文