Java14 동기 HttpClient 예제 – 개요 및 간단한 자습서 – send()
게시 됨: 2020-09-06 Java는 최근 Java 14
JDK를 출시했습니다. 이 자습서에서는 개요 및 단순 Java 동기 HttpClient 클라이언트 자습서를 살펴보겠습니다.
아래 질문 중 하나가 있으면 올바른 위치에 있습니다.
- JAVA에서 비동기 HTTP 요청을 생성하는 방법
- 동기 연결에 HttpClient를 사용하는 이유
- Java 11의 HttpClient에 대한 간단한 소개
- 자바 11 HTTP/2 API 튜토리얼
- 자바 HTTP 클라이언트 OpenJDK 소개
- Java HTTP 클라이언트 – 예제 및 레시피
HttpClient
를 사용하여 요청을 보내고 응답을 검색할 수 있습니다. HttpClient는 빌더를 통해 생성됩니다.
시작하자:
파일 생성 CrunchifyJavaSynchronousHTTPClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
package crunchify . com . tutorial ; import java . io . IOException ; import java . net . URI ; import java . net . http . HttpClient ; import java . net . http . HttpHeaders ; import java . net . http . HttpRequest ; import java . net . http . HttpResponse ; import java . time . Duration ; /** * @author Crunchify.com * Overview and Simple Java Synchronous HttpClient Client Tutorial */ public class CrunchifyJavaSynchronousHTTPClient { private static final HttpClient crunchifyHttpClient = HttpClient . newBuilder ( ) . version ( HttpClient . Version . HTTP_1_1 ) . connectTimeout ( Duration . ofSeconds ( 5 ) ) . build ( ) ; // HttpClient: An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder. // Duration: A time-based amount of time, such as '5 seconds'. // send() This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours. // In addition, the DAYS unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects. See Period for the date-based equivalent to this class. public static void main ( String [ ] args ) { HttpRequest crunchifyRequest = HttpRequest . newBuilder ( ) . GET ( ) . uri ( URI . create ( "https://crunchify.com/wp-content/java/crunchify-java-httpclient-tutorial.html" ) ) . setHeader ( "User-Agent" , "Crunchify Java Synchronous HTTPClient Example..." ) . build ( ) ; // HttpResponse: An HttpResponse is not created directly, but rather returned as a result of sending an HttpRequest. HttpResponse < String > crunchifyResponse = null ; try { // CompletableFuture: A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion. // send: Sends the given request using this client, blocking if necessary to get the response. // The returned HttpResponse<T> contains the response status, headers, and body ( as handled by given response body handler ). crunchifyResponse = crunchifyHttpClient . send ( crunchifyRequest , HttpResponse . BodyHandlers . ofString ( ) ) ; // print response headers HttpHeaders crunchifyHeaders = crunchifyResponse . headers ( ) ; crunchifyHeaders . map ( ) . forEach ( ( k , v ) - > System . out . println ( k + ":" + v ) ) ; // print status code crunnchifyPrint ( crunchifyResponse . statusCode ( ) ) ; // print response body crunnchifyPrint ( crunchifyResponse . body ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } private static void crunnchifyPrint ( Object data ) { System . out . println ( data ) ; } } |
crunchifyHttpClient.send()
자바 API는 이 클라이언트를 사용하여 주어진 요청을 보내고 응답을 받기 위해 필요한 경우 차단합니다.

반환된 HttpResponse<T>
에는 응답 상태, 헤더 및 본문(주어진 응답 본문 처리기에 의해 처리됨)이 포함됩니다.
위의 코드를 Java 프로그램으로 실행하면 아래와 같은 응답을 볼 수 있습니다.
콘솔 결과:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/ Library / Java / JavaVirtualMachines / jdk - 14.0.2.jdk / Contents / Home / bin / java - javaagent : / Applications / IntelliJ IDEA . app crunchify . com . tutorial . CrunchifyJavaSynchronousHTTPClient accept - ranges : [ bytes ] connection : [ keep - alive ] content - length : [ 108 ] content - type : [ text / html ; charset = UTF - 8 ] date : [ Sun , 06 Sep 2020 02 : 02 : 58 GMT ] etag : [ "5f5442af-6c" ] last - modified : [ Sun , 06 Sep 2020 02 : 00 : 15 GMT ] server : [ nginx ] x - edge - location - klb : [ VhPBsSUriL2dZtW2Pu8FgAke45e082923ff37191eace6947ec35b35d ] 200 < ! DOCTYPE html > < html > < body > < h1 > Hey . . This is Crunchify ' s Java HTTPClient Tutorial . < / h1 > < / body > < / html > Process finished with exit code 0 |
Java 코드 위에서 실행되는 문제에 직면하면 알려주십시오.
무엇 향후 계획?
Java 비동기 HttpClient 개요 및 자습서 – sendAsync()