케이스를 얻기 :
메이븐 프로젝트, 의존의 도입을 만들기 1. :
< 의존성 > <! - HttpClient를 -> < 의존성 > < 의 groupId > org.apache.httpcomponents </ 의 groupId > < artifactId를 > HttpClient를 </ artifactId를 > < 버전 > 4.5.3 </ 버전 > </ 의존성 > <! - 日志-> < 의존성 > < 의 groupId > org.slf4j </ 의 groupId > <artifactId를> SLF4J-log4j12 </ artifactId를 > < 버전 > 1.7.25 </ 버전 > </ 의존성 > <! - 의 JUnit -> < 의존성 > < 의 groupId > 의 JUnit </ 의 groupId > < artifactId를 > 의 JUnit </ artifactId를 > < 버전 > 4.12 </ 버전 > </ 의존성 > </ 의존성 >
2. 추가 log4j.properties
log4j.rootLogger = DEBUG, A1
log4j.logger.com.fgy = DEBUG
log4j.appender.A1 = org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout = org.apache.log4j.PatternLayout
log4j.appender.A1. layout.ConversionPattern % = - D {YYYY-MM-DD HH : MM : SS, SSS} [%의 t [%의 C] - [%의 P] m의 %의 % 않음
테스트 코드, 데이터 캡처를 작성합니다
@Test 공공 무효 testFirst는 () 던져 IOException가 { CloseableHttpClient 클라이언트 = HttpClients.createDefault를 (); HttpGet httpGet = 새로운 HttpGet ( "https://www.cnblogs.com/roadlandscape/" ); CloseableHttpResponse 응답 = client.execute (httpGet); 경우 (response.getStatusLine () getStatusCode () == 200. ) { 문자열 컨텍스트 = EntityUtils.toString (response.getEntity () "UTF-8" ); 에서 System.out.println (컨텍스트); } }
매개 변수를 GET 요청 :
@Test 공개 공극 testGetParam () { CloseableHttpClient 클라이언트 = HttpClients.createDefault (); // HttpGet httpGet = 새로운 HttpGet ( " https://s.taobao.com/search?q=vivo "); CloseableHttpResponse 응답 = 널 ; 시도 { URIBuilder 빌더 = 새 URIBuilder을 ( "https://s.taobao.com/search" ); builder.addParameter ( "Q", "생체" ); HttpGet httpGet = 새로운 HttpGet (builder.build ()); 응답 = client.execute (httpGet); 경우 (response.getStatusLine () getStatusCode () == 200. ) { 문자열 컨텍스트 = EntityUtils.toString (response.getEntity () "UTF-8" ); 에서 System.out.println (컨텍스트); } } 캐치 (예외 전자) { e.printStackTrace (); } 마지막으로 { 경우 (응답! = null이 ) { 시도 { response.close (); } 캐치 (IOException이 전자) { e.printStackTrace (); } } 시도 { () client.close; } 캐치 (IOException이 전자) { e.printStackTrace (); } } }
POST 요청 :
@Test 공개 공극 testPost () { CloseableHttpClient 클라이언트 = HttpClients.createDefault (); HttpPost httpPost = 새로운 HttpPost ( "https://www.cnblogs.com/roadlandscape/" ); CloseableHttpResponse 응답 = 널 ; 시도 { 응답 = client.execute (httpPost); 경우 (response.getStatusLine () getStatusCode () == 200. ) { 문자열 컨텍스트 = EntityUtils.toString (response.getEntity () "UTF-8" ); 에서 System.out.println (컨텍스트); } } 캐치 (IOException이 전자) { e.printStackTrace (); } 마지막으로 { 경우 (응답! = null이 ) { 시도 { response.close (); } 캐치 (IOException이 전자) { e.printStackTrace (); } } 시도 { ) (client.close을; } 캐치 (IOException이 전자) { e.printStackTrace (); } } }
매개 변수를 POST 요청 :
@Test 공개 공극 testPostParam () { CloseableHttpClient 클라이언트 = HttpClients.createDefault (); CloseableHttpResponse 응답 = 널 ; 시도 { HttpPost httpPost = 새로운 HttpPost ( "https://s.taobao.com/search" ); // 创建存放参数的목록 목록 <의 NameValuePair> PARAMS = 새로운 ArrayList를 <> (); params.add ( 새로운 BasicNameValuePair ( "Q", "생체" )); // 创建表单数据법인 UrlEncodedFormEntity 실체 = 새UrlEncodedFormEntity (PARAMS "UTF-8" ); // 设置表单엔티티到httpPost中 httpPost.setEntity (엔티티); 응답 = client.execute (httpPost); 경우 (response.getStatusLine () getStatusCode () == 200. ) { 문자열 컨텍스트 = EntityUtils.toString (response.getEntity () "UTF-8" ); 에서 System.out.println (컨텍스트); } } 캐치 (예외 전자) { e.printStackTrace (); } 마지막으로 { 경우 (응답! = null이 ) { 시도 { () response.close; } 캐치 (IOException이 전자) { e.printStackTrace (); } } 시도 { ) (client.close을; } 캐치 (IOException이 전자) { e.printStackTrace (); } } }
연결 풀링 :
각 요청 HttpClient를를 작성해야하는 경우,이 문제를 해결하기 위해 연결 풀링을 사용할 수 있습니다, 문제가 자주 만들고 파괴가있을 것입니다.
공용 클래스 ConPool { 공공 정적 무효 메인 (문자열 [] 인수)이 발생 IOException이 { PoolingHttpClientConnectionManager ㎝- = 새로운 새 ) PoolingHttpClientConnectionManager을 (; // 최대 연결의 수를 설정 cm.setMaxTotal (200이다 ); // 집합 동시 각 호스트의 개수 cm.setDefaultMaxPerRoute을 (20이다 ); 얻기위한 doGet (㎝-) } 개인 정적 무효 얻기위한 doGet (cm 및 PoolingHttpClientConnectionManager LT) 발생 IOException이 { CloseableHttpClient 클라이언트 =. HttpClients.custom () setConnectionManager (㎝-) .build (); HttpGet HttpGet = 새로운 새 HttpGet ( "https://www.cnblogs.com/roadlandscape/" ); // 설정 요청 파라미터 RequestConfig requestConfig = RequestConfig.custom () .setConnectTimeout ( 1000) // 연결을 만들 수있는 최대 시간으로 설정 .setConnectionRequestTimeout을 (500) // 검색된 최대 시간은 접속 설정 .setSocketTimeout (10 * 1000) // 설계 데이터의 최대 전송 시간 ) .build (; HttpGet .setConfig (requestConfig) CloseableHttpResponse 응답 = client.execute (HttpGet); 경우 (response.getStatusLine () getStatusCode () == 200. ) { 문자열 컨텍스트 = EntityUtils.toString (response.getEntity () "UTF-8" ); 에서 System.out.println (컨텍스트); } } }
1.1.1. 코드를 작성합니다