HttpClient 상세 사용 예시 상세 설명

29443 단어 HttpClient쓰다예시
HttpClient 는 Apache Jakarta Common 의 하위 프로젝트 로 효율 적 이 고 최신 이 며 기능 이 풍부 한 HTTP 프로 토 콜 을 지원 하 는 클 라 이언 트 프로 그래 밍 도 구 를 제공 할 수 있 으 며 HTTP 프로 토 콜 의 최신 버 전과 제안 을 지원 합 니 다.
HTTP 프로 토 콜 은 현재 인터넷 에서 가장 많이 사용 되 고 가장 중요 한 프로 토 콜 일 수 있 습 니 다.점점 더 많은 자바 응용 프로그램 이 HTTP 프로 토 콜 을 통 해 네트워크 자원 에 직접 접근 해 야 합 니 다.JDK 의 자바 넷 패키지 에 서 는 HTTP 프로 토 콜 에 접근 하 는 기본 기능 을 제 공 했 지만 대부분의 애플 리 케 이 션 에 서 는 JDK 라 이브 러 리 자체 가 제공 하 는 기능 이 풍부 하고 유연 하지 못 하 다.HttpClient 는 Apache Jakarta Common 의 하위 프로젝트 로 효율 적 이 고 최신 이 며 기능 이 풍부 한 HTTP 프로 토 콜 을 지원 하 는 클 라 이언 트 프로 그래 밍 도구 꾸러미 이 며 HTTP 프로 토 콜 의 최신 버 전과 제안 을 지원 합 니 다.
HTTP 는 브 라 우 저 와 비슷 하지만 브 라 우 저 는 아 닙 니 다.많은 사람들 이 HttpClient 가 HTTP 클 라 이언 트 프로 그래 밍 도구 이기 때문에 많은 사람들 이 그 를 브 라 우 저 로 이해 하지만 사실은 HttpClient 는 브 라 우 저 가 아니 라 HTTP 통신 라 이브 러 리 이기 때문에 유 니 버 설 브 라 우 저 프로그램 이 원 하 는 기능 부분 만 제공 합 니 다.가장 근본 적 인 차 이 는 HttpClient 에 사용자 인터페이스 가 없다 는 것 입 니 다.브 라 우 저 는 페이지 를 표시 하고 사용자 의 입력 을 설명 하 는 렌 더 링 엔진 이 필요 합 니 다.예 를 들 어 마 우 스 를 누 르 면 페이지 어 딘 가 에 레이아웃 엔진 이 있 습 니 다.HTML 페이지 를 어떻게 표시 하 는 지 계산 합 니 다.직렬 스타일 시트 와 이미 지 를 포함 합 니 다.javascript 해석 기 는 HTML 페이지 나 HTML 페이지 에서 인용 한 javascript 코드 를 실행 합 니 다.사용자 인터페이스 에서 온 이벤트 가 자바 script 해석 기 에 전달 되 어 처리 되 었 습 니 다.그 밖 에 플러그 인 에 사용 되 는 인터페이스 도 있 습 니 다.Applet,내장 형 미디어 대상(예 를 들 어 pdf 파일,Quicktime 영화,Flash 애니메이션)이나 ActiveX 컨트롤(모든 작업 을 수행 할 수 있 습 니 다)을 처리 할 수 있 습 니 다.HttpClient 는 API 를 통 해 HTTP 메 시 지 를 전송 하고 받 아들 일 수 있 도록 프로 그래 밍 할 수 있 습 니 다.
HttpClient 의 주요 기능:
  • 모든 HTTP 방법(GET,POST,PUT,HEAD,DELETE,HEAD,OPTIONS 등)을 실현 했다
  • HTTPS 프로 토 콜 지원
  • 프 록 시 서버 지원(Nginx 등)등4
  • 자동(점프)전환 지원
  • ……
  • 본론 으로 들어가다
    환경 설명:JDK 1.8,SpringBoot
    준비 단계 첫 번 째:pom.xml 에 HttpClient 의존 도입

    STEP 2:fastjson 의존 도입

    주:본인 이 이 의존 을 도입 한 목적 은 후속 예시 에서'대상 을 json 문자열 로 바 꾸 는 기능'을 사용 하고 이 기능 을 가 진 다른 의존 도 를 끌 어 올 리 는 것 입 니 다.
    주:SpringBoot 의 기본 의존 설정 은 더 이상 말 하지 않 겠 습 니 다.
    예 시 를 자세히 사용 하 다.
    성명:이 예제 에 서 는 JAVA 로 HttpClient(test 에서 유닛 테스트 로 보 낸)를 보 냅 니 다.JAVA 로 받 았 습 니 다.
    성명:아래 의 코드 는 본인 이 직접 측정 하면 유효 합 니 다.
    GET 무 참:
    HttpClient 에서 예제 보 내기:
    
    /**
    	 * GET---    
    	 *
    	 * @date 2018 7 13    4:18:50
    	 */
    	@Test
    	public void doGetTestOne() {
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    		//   Get  
    		HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerOne");
     
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//       (  )Get  
    			response = httpClient.execute(httpGet);
    			//             
    			HttpEntity responseEntity = response.getEntity();
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    GET 에 참조 가 있 습 니 다(방식 1:URL 을 직접 연결 합 니 다).
    HttpClient 에서 예제 보 내기:
    
    /**
    	 * GET---     (   :   url      )
    	 *
    	 * @date 2018 7 13    4:19:23
    	 */
    	@Test
    	public void doGetTestWayOne() {
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     
    		//   
    		StringBuffer params = new StringBuffer();
    		try {
    			//       encoding  ;    ,           ( :       “&”, encoding  ,    )
    			params.append("name=" + URLEncoder.encode("&", "utf-8"));
    			params.append("&");
    			params.append("age=24");
    		} catch (UnsupportedEncodingException e1) {
    			e1.printStackTrace();
    		}
     
    		//   Get  
    		HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//     
    			RequestConfig requestConfig = RequestConfig.custom()
    					//         (    )
    					.setConnectTimeout(5000)
    					//         (    )
    					.setConnectionRequestTimeout(5000)
    					// socket      (    )
    					.setSocketTimeout(5000)
    					//          (   true)
    					.setRedirectsEnabled(true).build();
     
    			//               Get   
    			httpGet.setConfig(requestConfig);
     
    			//       (  )Get  
    			response = httpClient.execute(httpGet);
     
    			//             
    			HttpEntity responseEntity = response.getEntity();
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    GET 에 참여(방식 2:URI 로 HttpGet 획득):
    HttpClient 에서 예제 보 내기:
    
     /**
    	 * GET---     (   :          ,   URI ,    URI  HttpGet  )
    	 *
    	 * @date 2018 7 13    4:19:23
    	 */
    	@Test
    	public void doGetTestWayTwo() {
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     
    		//   
    		URI uri = null;
    		try {
    			//          NameValuePair ,      
    			List<NameValuePair> params = new ArrayList<>();
    			params.add(new BasicNameValuePair("name", "&"));
    			params.add(new BasicNameValuePair("age", "18"));
    			//   uri  ,        uri;
    			//  :                    setParameter(String key, String value)
    			uri = new URIBuilder().setScheme("http").setHost("localhost")
    					 .setPort(12345).setPath("/doGetControllerTwo")
    					 .setParameters(params).build();
    		} catch (URISyntaxException e1) {
    			e1.printStackTrace();
    		}
    		//   Get  
    		HttpGet httpGet = new HttpGet(uri);
     
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//     
    			RequestConfig requestConfig = RequestConfig.custom()
    					//         (    )
    					.setConnectTimeout(5000)
    					//         (    )
    					.setConnectionRequestTimeout(5000)
    					// socket      (    )
    					.setSocketTimeout(5000)
    					//          (   true)
    					.setRedirectsEnabled(true).build();
     
    			//               Get   
    			httpGet.setConfig(requestConfig);
     
    			//       (  )Get  
    			response = httpClient.execute(httpGet);
     
    			//             
    			HttpEntity responseEntity = response.getEntity();
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    POST 무 참:
    HttpClient 에서 예제 보 내기:
    
     /**
    	 * POST---    
    	 *
    	 * @date 2018 7 13    4:18:50
    	 */
    	@Test
    	public void doPostTestOne() {
     
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     
    		//   Post  
    		HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerOne");
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//       (  )Post  
    			response = httpClient.execute(httpPost);
    			//             
    			HttpEntity responseEntity = response.getEntity();
     
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    POST 참조(일반 매개 변수):
    주:POST 가 일반 파 라 메 터 를 전달 할 때 방식 은 GET 와 같 으 면 됩 니 다.여기 서 url 접미사 에 파 라 메 터 를 직접 표시 합 니 다.
    HttpClient 에서 예제 보 내기:
    
    /**
    	 * POST---    (    )
    	 *
    	 * @date 2018 7 13    4:18:50
    	 */
    	@Test
    	public void doPostTestFour() {
     
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     
    		//   
    		StringBuffer params = new StringBuffer();
    		try {
    			//       encoding  ;    ,           ( :       “&”, encoding  ,    )
    			params.append("name=" + URLEncoder.encode("&", "utf-8"));
    			params.append("&");
    			params.append("age=24");
    		} catch (UnsupportedEncodingException e1) {
    			e1.printStackTrace();
    		}
     
    		//   Post  
    		HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerFour" + "?" + params);
     
    		//   ContentType( :           ,ContentType      application/json)
    		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
     
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//       (  )Post  
    			response = httpClient.execute(httpPost);
    			//             
    			HttpEntity responseEntity = response.getEntity();
     
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    POST 참조(대상 매개 변수):
    먼저 User 클래스 를 드 리 겠 습 니 다.

    HttpClient 에서 예제 보 내기:
    
    /**
    	 * POST---    (    )
    	 *
    	 * @date 2018 7 13    4:18:50
    	 */
    	@Test
    	public void doPostTestTwo() {
     
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     
    		//   Post  
    		HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerTwo");
    		User user = new User();
    		user.setName("   ");
    		user.setAge(18);
    		user.setGender(" ");
    		user.setMotto("     ~");
    		//         fastjson, Object   json   ;
    		// (    com.alibaba.fastjson.JSON )
    		String jsonString = JSON.toJSONString(user);
     
    		StringEntity entity = new StringEntity(jsonString, "UTF-8");
     
    		// post                 ;   entity  post    
    		httpPost.setEntity(entity);
     
    		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
     
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//       (  )Post  
    			response = httpClient.execute(httpPost);
    			//             
    			HttpEntity responseEntity = response.getEntity();
     
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    POST 참조(일반 매개 변수+대상 매개 변수):
    주의:POST 가 일반 인 자 를 전달 할 때 방식 은 GET 와 같 으 면 됩 니 다.여 기 는 URI 를 통 해 HttpPost 를 얻 는 방식 을 예 로 들 수 있 습 니 다.
    먼저 User 클래스 를 드 립 니 다:

    HttpClient 에서 예제 보 내기:
    
    /**
    	 * POST---    (     +     )
    	 *
    	 * @date 2018 7 13    4:18:50
    	 */
    	@Test
    	public void doPostTestThree() {
     
    		//   Http   (     :         ;  :   HttpClient         )
    		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     
    		//   Post  
    		//   
    		URI uri = null;
    		try {
    			//          NameValuePair ,      
    			List<NameValuePair> params = new ArrayList<>();
    			params.add(new BasicNameValuePair("flag", "4"));
    			params.add(new BasicNameValuePair("meaning", "     ?"));
    			//   uri  ,        uri;
    			//  :                    setParameter(String key, String value)
    			uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(12345)
    					.setPath("/doPostControllerThree").setParameters(params).build();
    		} catch (URISyntaxException e1) {
    			e1.printStackTrace();
    		}
     
    		HttpPost httpPost = new HttpPost(uri);
    		// HttpPost httpPost = new
    		// HttpPost("http://localhost:12345/doPostControllerThree1");
     
    		//   user  
    		User user = new User();
    		user.setName("   ");
    		user.setAge(18);
    		user.setGender(" ");
    		user.setMotto("     ~");
     
    		//  user     json   ,   entity 
    		StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
     
    		// post                 ;   entity  post    
    		httpPost.setEntity(entity);
     
    		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
     
    		//     
    		CloseableHttpResponse response = null;
    		try {
    			//       (  )Post  
    			response = httpClient.execute(httpPost);
    			//             
    			HttpEntity responseEntity = response.getEntity();
     
    			System.out.println("     :" + response.getStatusLine());
    			if (responseEntity != null) {
    				System.out.println("       :" + responseEntity.getContentLength());
    				System.out.println("     :" + EntityUtils.toString(responseEntity));
    			}
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				//     
    				if (httpClient != null) {
    					httpClient.close();
    				}
    				if (response != null) {
    					response.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    대응 수신 예시:

    평론 구역 의 관심 도가 비교적 높 은 문제 에 대해 관련 보충 을 한다.
    알림:완전한 구체 적 인 코드 와 테스트 디 테 일 을 알 고 싶 으 면 아래 에 있 는 프로젝트 코드 위탁 관리 링크 로 가서 프로젝트 클 라 이언 트 를 내 려 놓 을 수 있 습 니 다.
    관찰 하 다.테스트 를 실행 하려 면 이 SpringBoot 프로젝트 를 시작 한 다음 에 관련 test 방법 을 실행 하여 진행 할 수 있 습 니 다.
    테스트
    응답 오류 해결(예시):

    HTTPS 요청 을 하고 인증서 검사(예시)를 수행 합 니 다.
    사용 예시:

    관련 방법 상세 정보(완벽 하지 않 은 패키지):
    
    /**
     *      https  ,  HttpClient   
     *
     * TODO             。              ,       
     *       ,      ,        。
     *
     *   :        、     、        ,         :
     * <linked>https://blog.csdn.net/justry_deng/article/details/91569132</linked>
     *
     *
     * @param isHttps    HTTPS  
     *
     * @return HttpClient  
     * @date 2019/9/18 17:57
     */
    private CloseableHttpClient getHttpClient(boolean isHttps) {
     CloseableHttpClient httpClient;
     if (isHttps) {
     SSLConnectionSocketFactory sslSocketFactory;
     try {
     ///           
     sslSocketFactory = getSocketFactory(false, null, null);
     
     ///           
     //   
     //InputStream ca = this.getClass().getClassLoader().getResourceAsStream("client/ds.crt");
     //      , :key。  :cAalias         ,        keystore      。
     // String cAalias = System.currentTimeMillis() + "" + new SecureRandom().nextInt(1000);
     //sslSocketFactory = getSocketFactory(true, ca, cAalias);
     } catch (Exception e) {
     throw new RuntimeException(e);
     }
     httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
     return httpClient;
     }
     httpClient = HttpClientBuilder.create().build();
     return httpClient;
    }
     
    /**
     * HTTPS    ,  HTTPS     SSLSocketFactory  、TrustManager  
     *
     * @param needVerifyCa
     *       CA  ( :            )
     * @param caInputStream
     * CA  。(        ,     null  )
     * @param cAalias
     *   。(        ,     null  )
     *   :        ,             ,                 。   key-value  key。
     *
     * @return SSLConnectionSocketFactory  
     * @throws NoSuchAlgorithmException
     *     
     * @throws CertificateException
     *     
     * @throws KeyStoreException
     *     
     * @throws IOException
     *     
     * @throws KeyManagementException
     *     
     * @date 2019/6/11 19:52
     */
    private static SSLConnectionSocketFactory getSocketFactory(boolean needVerifyCa, InputStream caInputStream, String cAalias)
     throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
     IOException, KeyManagementException {
     X509TrustManager x509TrustManager;
     // https  ,      
     if (needVerifyCa) {
     KeyStore keyStore = getKeyStore(caInputStream, cAalias);
     TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     trustManagerFactory.init(keyStore);
     TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
     if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
     throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
     }
     x509TrustManager = (X509TrustManager) trustManagers[0];
     //    TLS SSL      
     SSLContext sslContext = SSLContext.getInstance("TLS");
     sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
     return new SSLConnectionSocketFactory(sslContext);
     }
     // https  ,      
     x509TrustManager = new X509TrustManager() {
     @Override
     public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
     }
     
     @Override
     public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
     //    
     }
     
     @Override
     public X509Certificate[] getAcceptedIssuers() {
     return new X509Certificate[0];
     }
     };
     SSLContext sslContext = SSLContext.getInstance("TLS");
     sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
     return new SSLConnectionSocketFactory(sslContext);
    }
     
    /**
     *   (     )  
     *  :              
     *
     * @param caInputStream
     * CA  (              )
     * @param cAalias
     *   
     *   :        ,             ,                 。   key-value  key。
     * @return   、     
     * @throws KeyStoreException     
     * @throws CertificateException     
     * @throws IOException     
     * @throws NoSuchAlgorithmException     
     * @date 2019/6/11 18:48
     */
    private static KeyStore getKeyStore(InputStream caInputStream, String cAalias)
     throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
     //     
     CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
     //     
     KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
     keyStore.load(null);
     keyStore.setCertificateEntry(cAalias, certificateFactory.generateCertificate(caInputStream));
     return keyStore;
    }
    application/x-www-form-urlencoded 폼 요청(예제):

    파일 보 내기(예시):
    준비 작업:
    유연 하고 편리 하 게 파일 을 전송 하려 면 org.apache.httpcomponents 기본 httpclient 의존 외 에 org.apache.httpcomponents 의 httpmime 의존 도 를 추가 로 도입 합 니 다.
    P.S.:httpmime 의존 을 도입 하지 않 아 도 파일 을 전송 할 수 있 지만 기능 이 강하 지 않 습 니 다.
    pom.xml 에 추가 도입:
    
    <!--
                ,           
    -->
    <dependency>
    	<groupId>org.apache.httpcomponents</groupId>
    	<artifactId>httpmime</artifactId>
    	<version>4.5.5</version>
    </dependency>
    송신 단 은 다음 과 같 습 니 다:
    
    /**
     *
     *     
     *
     * multipart/form-data    (     )
     *
     *  :               ,
     *     org.apache.httpcomponents   httpclient   
     *      org.apache.httpcomponents httpmime  。
     *   :     httpmime  ,        ,        。
     *
     */
    @Test
    public void test4() {
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     HttpPost httpPost = new HttpPost("http://localhost:12345/file");
     CloseableHttpResponse response = null;
     try {
     MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
     //      
     String filesKey = "files";
     File file1 = new File("C:\\Users\\JustryDeng\\Desktop\\back.jpg");
     multipartEntityBuilder.addBinaryBody(filesKey, file1);
     //      (      ,     key  ,              )
     File file2 = new File("C:\\Users\\JustryDeng\\Desktop\\  .jpg");
     //              。            URLEncode,            URLDecode。        。
     //             Content-Disposition       ,    form-data; name="files"; filename="  .jpg"
     multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
     //     ( :   contentType,  UTF-8                 )
     ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
     multipartEntityBuilder.addTextBody("name", "    ", contentType);
     multipartEntityBuilder.addTextBody("age", "25", contentType);
     
     HttpEntity httpEntity = multipartEntityBuilder.build();
     httpPost.setEntity(httpEntity);
     
     response = httpClient.execute(httpPost);
     HttpEntity responseEntity = response.getEntity();
     System.out.println("HTTPS     :" + response.getStatusLine());
     if (responseEntity != null) {
     System.out.println("HTTPS       :" + responseEntity.getContentLength());
     //       ,       
     String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
     System.out.println("HTTPS     :" + responseStr);
     }
     } catch (ParseException | IOException e) {
     e.printStackTrace();
     } finally {
     try {
     //     
     if (httpClient != null) {
     httpClient.close();
     }
     if (response != null) {
     response.close();
     }
     } catch (IOException e) {
     e.printStackTrace();
     }
     }
    }
    수신 단 은 다음 과 같 습 니 다:

    전송 흐름(예시):
    송신 단 은 다음 과 같 습 니 다:
    
    /**
     *
     *    
     *
     */
    @Test
    public void test5() {
     CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     HttpPost httpPost = new HttpPost("http://localhost:12345/is?name=    ");
     CloseableHttpResponse response = null;
     try {
     InputStream is = new ByteArrayInputStream("   ~".getBytes());
     InputStreamEntity ise = new InputStreamEntity(is);
     httpPost.setEntity(ise);
     
     response = httpClient.execute(httpPost);
     HttpEntity responseEntity = response.getEntity();
     System.out.println("HTTPS     :" + response.getStatusLine());
     if (responseEntity != null) {
     System.out.println("HTTPS       :" + responseEntity.getContentLength());
     //       ,       
     String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
     System.out.println("HTTPS     :" + responseStr);
     }
     } catch (ParseException | IOException e) {
     e.printStackTrace();
     } finally {
     try {
     //     
     if (httpClient != null) {
     httpClient.close();
     }
     if (response != null) {
     response.close();
     }
     } catch (IOException e) {
     e.printStackTrace();
     }
     }
    }
    수신 단 은 다음 과 같 습 니 다:

    다시 한 번 알림:테스트 를 하려 면 아래 에 있 는 프로젝트 코드 위탁 관리 링크 로 가서 프로젝트 클 라 이언 트 를 내 려 놓 고 먼저 시작 할 수 있 습 니 다.
    SpringBoot 프로젝트 를 실행 한 후 관련 test 방법 을 실행 하여 테스트 합 니 다.
    도구 클래스 알림:HttpClient 를 사용 할 때 상황 에 따라 도구 클래스 로 쓸 수 있 습 니 다.Github 에서 Star 가 매우 많은 HttpClient
    의 도구 클래스 는 http clientutil 입 니 다.저 는 여기 서도 이 도구 류 를 사용 하 는 것 을 추천 합 니 다.이 도구 류 의 작성 자 는 패키지 되 어 있 기 때 문 입 니 다.
    많은 기능 이 안에 있 습 니 다.특별한 수요 가 없 으 면 바퀴 를 만 들 지 않 고 직접 사용 할 수 있 습 니 다.
    이 공구 류.사용 방식 이 매우 간단 하 니 상세 하 게 볼 수 있다.
    여기 서 HttpClient 에 대한 상세 한 사용 예시 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 HttpClient 사용 예시 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

    좋은 웹페이지 즐겨찾기