RestTemplate 사용의 예를 작성했습니다. Spring 5는 반응성을 완전히 소개하고 RestTemplate의 웹 클리어의 반응성 버전을 보유하고 있기 때문에이 기사는 WebClient의 기본 사용을 보여줍니다.
헤더를 운반하도록 요청합니다
쿠키를 가지고 다니십시오
@test public void testwithCookie () {mono <string> resp = webclient.create () .method (httpmethod.get) .uri ( "http://baidu.com") .cookie ( "토큰", "xxxx") .cookie ( "jsessionid", "xxxx". .BodyTomono (String.class); logger.info ( "결과 : {}", resp.block ()); } 기본 인증을 가지고 다니십시오
@test public void testwithbasicauth () {String basicauth = "Basic"+ base64.getEncoder (). encodetostring ( "사용자 : pwd".getBytes (Standardcharsets.utf_8)); logger.info (Basicauth); mono <string> resp = webclient.create () .get () .uri ( "http://baidu.com") .Header (httpheaders.authorization, basicauth) .retrieve () .bodytomono (String.class); logger.info ( "결과 : {}", resp.block ()); } 글로벌 사용자 에이전트를 설정하십시오
@test public void testwithHeaderFilter () {WebClient webClient = webClient.builder () .defaultheAder (httpheaders.user_agent, "Mozilla/5.0 (Macintosh; Intel Mac OS x 10_12_6) AppleWebkit/537.36 (khtml, gecko) 23232223222322232323232322323222322232322323222322322232223223222322322322332232233233232232232222322322232 Safari/537.36") .filter(ExchangeFilterFunctions .basicAuthentication("user","password")) .filter((clientRequest, next) -> { LOGGER.info("Request: {} {}", clientRequest.method(), clientRequest.url()); clientRequest.headers() .forEach((name, values) -> 값. mono <string> resp = webclient.get () .uri ( "https://baidu.com") .retrieve () .bodytomono (String.class); logger.info ( "결과 : {}", resp.block ()); }요청 받으십시오
자리 표시자를 사용하여 매개 변수를 전달합니다
@test public void testurlplaceholder () {mono <string> resp = webclient.create () .get () // 여러 매개 변수도 맵에 직접 배치 할 수 있고 매개 변수 이름은 vactholder.uri ( "http://www.baidu.com/s ?s?wd= {Kother= {another}")에 해당합니다. 위장기 .retrieve () .BodyTomono (String.class); logger.info ( "결과 : {}", resp.block ()); } Uribuilder를 사용하여 매개 변수를 전달합니다
@test public void testurlbiulder () {mono <string> resp = webclient.create () .get () .uri (uribuilder-> uribuilder .scheme ( "http") .host ( "www.baidu.com") .path ( "/s") .QueryParam ( "wd" "test") .build ()) .retrieve () .bodytomono (String.class); logger.info ( "결과 : {}", resp.block ()); }포스트 양식
@test public void testformparam () {multivaluemap <string, string> formdata = new LinkedMultivaluemap <> (); formdata.add ( "name1", "value1"); formdata.add ( "name2", "value2"); mono <string> resp = webclient.create (). post () .uri ( "http://www.w3school.com.cn/test/demo_form.asp") .contentType (mediaType.application_form_urlencoded). .retrieve (). BodyTomono (String.class); logger.info ( "결과 : {}", resp.block ()); }Post JSON
콩을 사용하여 게시하십시오
정적 클래스 북 {문자열 이름; 문자열 제목; 공개 문자열 getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public string getTitle () {return title; } public void settitle (문자열 제목) {this.title = title; }} @test public void testpostjson () {book book = new Book (); book.setName ( "이름"); book.settitle ( "이것은 제목입니다"); mono <string> resp = webclient.create (). post () .uri ( "http : // localhost : 8080/demo/json") logger.info ( "결과 : {}", resp.block ()); } 직접 게시물 RAW JSON
@test public void testpostrawjson () {mono <string> resp = webclient.create (). post () .uri ( "http : // localhost : 8080/demo/json") title/",/n" + "/"author/":/"이것은 author/"/n" + "}")) .retrieve (). bodytomono (string.class); logger.info ( "결과 : {}", resp.block ()); }이진-upload 파일을 게시합니다
@test public void testuploadfile () {httpheaders headers = new httpheaders (); headers.setContentType (mediaType.Image_png); httpentity <classpathresource> entity = new httpentity <> (New ClassPathResource ( "Palement.Png"), 헤더); multivaluemap <string, object> parts = new LinkedMultivaluemap <> (); parts.add ( "파일", 엔티티); mono <string> resp = webclient.create (). post () .uri ( "http : // localhost : 8080/upload") logger.info ( "결과 : {}", resp.block ()); }이진을 다운로드하십시오
사진을 다운로드하십시오
@test public void testdownloadimage ()는 ioexception을 던지고 ioexception {mono <resource> resp = webclient.create (). get () .uri ( "http://www.toolip.gr/captcha?complexity=99&size=60&length=9") .Accept (mediaType.image. .retrieve (). BodyTomono (resource.class); 자원 자원 = resp.Block (); bufferedImage bufferedImage = imageio.Read (resource.getInputStream ()); imageio.write (bufferedImage, "png", 새 파일 ( "captcha.png")); } 파일을 다운로드하십시오
@test public void testdownloadfile ()는 ioexception을 던지려고 {mono <clientResponse> resp = webclient.create (). get () .uri ( "http : // localhost : 8080/file/download") ClientResponse Response = resp.Block (); 문자열 배치 = response.headers (). ashttpheaders (). getfirst (httpheaders.content_disposition); 문자열 filename = clisposition.substring (cutposition.indexof ( "=")+1); 자원 자원 = 응답. 파일 out = 새 파일 (filename); fileUtils.copyInputStreamTofile (resource.getInputStream (), Out); logger.info (out.getabsolutepath ()); }오류 처리
@Test public void testReque4xx () {webclient webclient = webclient.builder () .baseurl ( "https://api.github.com") .defaultheader (httppeaders.content_type, "application/vnd.github.v3+json") .defaultheader (httpheaders.user_agent, "Spring 5 WebClient") .Build (); webClient.RespOsSeSpec responseSpec = webClient.Method (httpMethod.get) .uri ( "/user/repos? sort = {sortfield} & direction = {sortDirection}", "업데이트", "desc") .retrieve (); mono <string> mono = responsespec .onstatus (e-> e-> e.is4xxclienterRor (), resp-> {logger.error ( "error : {}, msg : {}", resp.statuscode (). + ":" + resp.statuscode (). getReasonPhrase ())); runtimeexception (err.getMessage ()); 문자열 결과 = mono.block (); logger.info ( "결과 : {}", 결과); }요약
WebClient는 새로운 세대의 비동기 REST 템플릿이며 API는 비교적 단순하고 반응성이 있으며 사용 가치가 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.