multithreading - Java HttpClient 4.5.2: the thread hangs after the logger outputs "Starting handshake" -
i create spider using java , chose httpclient4.5.2 deal http request. multithreading. when running 1 of thread hangs after few minutes , last log "debug:starting handshake". hangs no error output.
it needs execute lots of httprequset. not sure if connection not close correctly or maybe stack overflow.
the following httpclient part of code.
public static string get(string url,string proxyhost,string proxyport) throws ioexception { httpclientbuilder httpclientbuilder = httpclientbuilder.create(); //httpclient closeablehttpclient closeablehttpclient = httpclientbuilder.build(); httpget httpget = new httpget(url); requestconfig requestconfig = null; httpget.setheader("accept", "accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpget.setheader("accept-charset", "gb2312,utf-8;q=0.7,*;q=0.7"); httpget.setheader("accept-encoding", "gzip, deflate"); httpget.setheader("accept-language", "zh-cn,zh;q=0.5"); httpget.setheader("connection", "keep-alive"); httpget.setheader("user-agent", "mozilla/5.0 (windows nt 6.1; rv:6.0.2) gecko/20100101 firefox/6.0.2"); if(proxyhost != null && proxyport != null) { httphost proxy = new httphost(proxyhost, new integer(proxyport).intvalue()); requestconfig = requestconfig.custom() .setconnectionrequesttimeout(5000).setconnecttimeout(5000) .setsockettimeout(5000).setproxy(proxy).build(); }else{ requestconfig = requestconfig.custom() .setconnectionrequesttimeout(2000).setconnecttimeout(2000) .setsockettimeout(2000).build(); } httpget.setconfig(requestconfig); httpresponse httpresponse = null; httpentity entity = null; try { httpresponse = closeablehttpclient.execute(httpget); entity = httpresponse.getentity(); string html = null; if (entity == null) return null; else { byte[] bytes = new byte[1024*1024]; inputstream = entity.getcontent(); int offset = 0; int numread = 0; while(offset < bytes.length && (numread = is.read(bytes, offset, bytes.length-offset)) != -1) offset+=numread; html = new string(bytes,0,offset,"utf-8"); string charset = getcharset(html); if(charset == null || charset.equals("utf8") || charset.equals("utf-8")) return html; else html = new string(bytes,0,offset,charset); return html; } } { try { //关闭流并释放资源 if(entity!=null) entityutils.consume(entity); if(closeablehttpclient!= null) closeablehttpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } }
Comments
Post a Comment