Saya telah menulis contoh penggunaan RestTemplate. Karena Spring 5 sepenuhnya memperkenalkan reaktif dan juga memiliki versi reaktif dari WebClient RestTemplate, artikel ini akan menunjukkan penggunaan dasar WebClient.
Permintaan untuk membawa header
Membawa cookie
@Test public void testwithcookie () {mono <string> resp = webclient.create () .method (httpmethod.get) .uri ("http://baidu.com") .cookie ("Token", "xxxx") .cookie ("jsessionid", "xxxx). Logger.info ("hasil: {}", resp.block ()); } Membawa auth dasar
@Test public void testWithBasiCiauth () {string basicAuth = "dasar"+ base64.getEncoder (). EncodeToString ("pengguna: pwd" .getbytes (standardcharsets.utf_8)); Logger.info (BasicAuth); Mono <string> resp = webclient.create () .get () .uri ("http://baidu.com") .Header (httpheaders.authorisasi, basicauth) .retrieve () .bodytomono (string.class); Logger.info ("hasil: {}", resp.block ()); } Setel agen pengguna global
@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, like Gecko) Chrome/63.0.3239.132 Safari/537.36 ") .filter (ExchangeFilterFunctions .BasicAuthentication (" User "," Password ")) .filter ((ClientRequest, Next) -> {Logger.info (" Permintaan: {} {}), clientRequest.method (), clientrequest.ur ({{{}), clientrequest.method (), clientrequest.ur. -> value.foreach (nilai -> logger.info ("{} = {}", name, value))); Mono <string> resp = webclient.get () .uri ("https://baidu.com") .retrieve () .bodytomono (string.class); Logger.info ("hasil: {}", resp.block ()); }Dapatkan permintaan
Lulus parameter menggunakan placeholder
@Test public void testurlplaceHolder () {mono <string> resp = webclient.create () .get () // Beberapa parameter juga dapat ditempatkan langsung di peta, dan nama parameter sesuai dengan placeholder.uri ("http://www.baidu.com/s?wd=.Key})" "http:/www.baidu.com/s?wd=.key=." placeholder.retrieve () .BodyTomono (String.class); Logger.info ("hasil: {}", resp.block ()); } Lulus parameter menggunakan uribuilder
@Test public void testurlbiulder () {mono <string> resp = webclient.create () .get () .uri (Uribuilder -> Uribuilder .scheme ("http") .host ("www.baidu.com") .path ("/s"). "tes") .build ()) .retrieve () .bodytomono (string.class); Logger.info ("hasil: {}", resp.block ()); }Formulir Posting
@Test public void testFormParam () {multivaluemap <string, string> formdata = new LinkedMulliValUeMap <> (); 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) .body (bodyinserty.fromformData (formdication) .body) .bodyserty (FormFromformData (formdication) .bodySters.FromformDATA (FORMDACEDECODED) .BODINSERTERS.FROMFORMDATED)). .Retrieve (). Bodytomono (String.class); Logger.info ("hasil: {}", resp.block ()); }Posting JSON
Gunakan kacang untuk memposting
Buku kelas statis {string name; Judul string; public string getName () {return name; } public void setName (name string) {this.name = name; } public String getTitle () {return title; } public void setTitle (string title) {this.title = title; }} @Test public void testPostjson () {Buku buku = buku baru (); book.setname ("name"); book.settitle ("This is Title"); Mono<String> resp = WebClient.create().post() .uri("http://localhost:8080/demo/json") .contentType(MediaType.APPLICATION_JSON_UTF8) .body(Mono.just(book),Book.class) .retrieve().bodyToMono(String.class); Logger.info ("hasil: {}", resp.block ()); } POST LANGSUNG JSON RAW
@Test public void testpostrawjson () {mono <string> resp = webclient.create (). Post () .uri ("http: // localhost: 8080/demo/json") .contentType (mediatype.application_json_utf8) .body (bodyinserTer.from ("" "" "" "" " judul/",/n" + "/" penulis/":/" Ini adalah penulis/"/n" + "}")) .retrieve (). BodyTomono (String.class); Logger.info ("hasil: {}", resp.block ()); }Posting File Biner-Upload
@Test public void testUploadFile () {httpheaders headers = httpheaders baru (); headers.setContentType (mediatype.image_png); Httpentity <ClassPathResource> entitas = httpentity baru <> (classpathResource baru ("paralel.png"), header); Multivaluemap <string, object> bagian = LinkedMullivaluemap <> () baru; parts.add ("file", entitas); Mono <string> resp = webclient.create (). Post () .uri ("http: // localhost: 8080/unggah") .contentType (mediatype.multipart_form_data) .body (bodyinserters.fromultipartdata (bagian)). Logger.info ("hasil: {}", resp.block ()); }Unduh biner
Unduh gambarnya
@Test public void testDownloadImage() throws IOException { Mono<Resource> resp = WebClient.create().get() .uri("http://www.toolip.gr/captcha?complexity=99&size=60&length=9") .accept(MediaType.IMAGE_PNG) .Retrieve (). Bodytomono (Resource.class); Sumber daya sumber daya = resp.block (); BufferedImage bufferedImage = imageIO.read (resource.getInputStream ()); Imageo.write (bufferedImage, "png", file baru ("captcha.png")); } Unduh file
@Test public void testdownloadFile () melempar ioException {mono <ClientResponse> resp = webclient.create (). Get () .uri ("http: // localhost: 8080/file/download") .cepcept (mediatype.application_octet_stream) .exchange (); Respons respon klien = resp.block (); String disposition = response.headers (). Ashttpheaders (). GetFirst (httpheaders.content_disposition); String filename = disposition.substring (disposition.indexof ("=")+1); Sumber Daya Sumber Daya = Response.BodyTomono (Resource.class) .block (); File out = file baru (nama file); Fileutils.copyInputStreamToFile (resource.getInputStream (), out); Logger.info (out.getAbsolutePath ()); }Penanganan kesalahan
@Test public void testRetrieve4xx () {webclient webclient = webclient.builder () .baseUrl ("https://api.github.com") .defaultheader (httpheaders.content_type, "Application/vnd.github.v3+Jon+Json)) .defaulTheader (httpheaders.user_agent, "spring 5 webclient") .build (); WebClient.Responsespec responseSpec = webclient.method (httpmethod.get) .uri ("/user/repo? Sort = {sortfield} & arah = {sortDirection}", "diperbarui", "desc") .retrieve (); Mono <string> mono = responseSpec .onstatus (e -> e.is4xxclientError (), resp -> {logger.error ("error: {}, msg: {}", resp.statuscode (); value (), resp.statusCode (). GetReasonPhrase (); return (), resp.statuscode (). GetReasonPhase (); RunimeException (resp.statuscode (). Value () + ":" + resp.statuscode (). GetReasonPhrase ())); Status: {}, msg: {} ", err.getRawstatusCode (), err.getResponseBodyString ()); lempar runtimeException baru (err.getMessage ());}) .onerrorreturn (" fallback "); Hasil string = mono.block (); Logger.info ("hasil: {}", hasilnya); }ringkasan
WebClient adalah generasi baru dari Templat Istirahat Async, dan API relatif sederhana dan reaktif, yang sangat layak digunakan.
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.