참고 : 다음 코드는 httpclient4.5.2를 기반으로합니다.
Java의 httpclient를 사용하여 웹 페이지의 GET 요청 크롤링을 구현하는 것이 더 쉬운 작업입니다.
public static string get (string url) {closeablehttpresponsponsponse = null; 버퍼드 리더 in = null; 문자열 결과 = ""; try {closeablehttpclienthttpplient = httpclients.createdefault (); httpgethttpget = new httpget (url); 응답 = httppclient.execute (httpget); in = new bufferedReader (new inputStreamReader (response.getentity (). getContent ()); StringBuffersB = New StringBuffer ( ""); 문자열 line = ""; 문자열 nl = system.getProperty ( "line.separator"); while ((line = in.readline ())! = null) {sb.append (line + nl); } in.close (); 결과 = sb.tostring (); } catch (ioexception e) {e.printstacktrace (); } 마침내 {try {if (null! = response) response.close (); } catch (ioexception e) {e.printstacktrace (); }} 반환 결과; }위의 방법은 GET 요청을 멀티 스레드 실행 할 때도 유용합니다. 그러나이 다중 스레드 요청은 Get 메소드가 호출 될 때마다 HTTPCLIENT 인스턴스를 작성하는 것을 기반으로합니다. 각 httpclient 인스턴스는 한 번 재활용됩니다. 이것은 분명히 최적의 구현이 아닙니다.
httpclient는 다중 스레드 요청 솔루션을 제공하며 공식 문서 "Pooling Connection Manager"를 볼 수 있습니다. httpclient 구현 다중 스레드 요청은 주요 클래스, 즉 Httpclient Connection Pool을 관리하는 핵심 클래스, 즉 PoolinghttpclientConnectionManager를 기반으로 구현됩니다. poolinghttpclientConnectionManager에는 SetMaxtOtal 및 setDefaultMaxPerroute에서 사용할 수있는 두 가지 주요 방법이 있습니다. setMaxtotal은 연결 풀에 최대 연결 수를 설정하고 SetDefaultMaxperRoute는 각 경로에서 기본 연결 수를 설정합니다. SetMaxPerroute 메소드도 있습니다.
httphosthost = new httphost ( "locahost", 80); cm.setmaxperroute (New Httproute (호스트), 50);
GET 요청 구현은 문서에 따라 약간 조정됩니다.
패키지 com.zhyea.robin; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httpget; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.htpclients; org.apache.http.impl.conn.poolinghttpclientConnectionManager; import java.io.bufferedReader; import java.io.ioexception; import java.io.inputStreamReader; 공개 클래스 httputil {private static closeblehttpclienthttpclient; static {poolinghttpclientConnectionManagercm = 새로운 poolinghttpclientConnectionManager (); cm.setmaxtotal (200); cm.setDefaultMaxPerroute (20); cm.setDefaultMaxPerroute (50); httpclient = httpclients.custom (). setConnectionManager (cm) .build (); } public static string get (String URL) {closeablehttpresponsponse = null; bufferedReaderIn = null; 문자열 결과 = ""; try {httpgethttpget = new httpget (url); 응답 = httpclient.execute (httpget); in = new bufferedReader (new inputStreamReader (response.getentity (). getContent ()); StringBuffersB = New StringBuffer ( ""); 문자열 line = ""; 문자열 nl = system.getProperty ( "line.separator"); while ((line = in.readline ())! = null) {sb.append (line + nl); } in.close (); 결과 = sb.tostring (); } catch (ioexception e) {e.printstacktrace (); } 마침내 {try {if (null! = response) response.close (); } catch (ioexception e) {e.printstacktrace (); }} 반환 결과; } public static void main (String [] args) {System.out.println (get ( "https://www.baidu.com/"); }}그것에 관한 것입니다. 그러나 저는 HTTP Pclient의 유창한 구현을 선호합니다. 예를 들어, 방금 구현 한 HTTP get 요청은 다음과 같이 구현할 수 있습니다.
패키지 com.zhyea.robin; import org.apache.http.client.fluent.request; import java.io.ioexception; public class httputil {public static string get (string url) {문자열 result = ""; try {result = request.get (url) .connectTimeout (1000) .sockettimeout (1000) .Execute (). returnContent (). asstring (); } catch (ioexception e) {e.printstacktrace (); } 반환 결과; } public static void main (String [] args) {System.out.println (get ( "https://www.baidu.com/"); }}우리가해야 할 일은 이전 httpclient 의존성을 fluent-HC 의존성으로 바꾸는 것입니다.
<pectionency> <groupid> org.apache.httpcomponents </groupid> <artifactid> fluent-hc </artifactid> <버전> 4.5.2 </version> </fectionency>
그리고이 유창한 구현은 poolinghttpclientConnectionManager를 사용하여 자연스럽게 달성됩니다. 설정 한 MAXTOTAL 및 DEFAULTMAXPERROUTE의 값은 각각 200과 100입니다.
connmgr = 새로운 poolinghttpclientConnectionManager (SFR); connmgr.setDefaultMaxPerroute (100); connmgr.setmaxtotal (200);
사람들이 화를내는 유일한 것은 집행자 가이 두 값을 조정하는 방법을 제공하지 않는다는 것입니다. 그러나 이것은 충분합니다. 실제로 작동하지 않으면 집행자 메소드를 다시 작성한 다음 집행자를 직접 사용하여 GET 요청을 실행할 수도 있습니다.
executor.newinstance (). execute (request.get (url)) .returnContent (). astring ();
그게 다야!