لقد كتبت مثالا على الاستخدام. نظرًا لأن Spring 5 تقدم بالكامل Reactive ولديها أيضًا نسخة تفاعلية من WebClient من RestTemplate ، فستظهر هذه المقالة الاستخدام الأساسي لـ WebClient.
طلب حمل الرأس
حمل ملفات تعريف الارتباط
Test public void testWithCoOkie () {mono <string> resp = webclient.create () .method (httpmethod.get) .uri ("http://baidu.com") .cookie ("token" ، "xxxx") .cookie ( .bodyTomono (String.Class) ؛ logger.info ("النتيجة: {}" ، resp.block ()) ؛ } حمل المصادقة الأساسية
test public void testWithBasicauth () {String basicauth = "basic"+ base64.getencoder (). encodetoString ("user: 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) Safari/537.36 ") .filter (ExchangeFilterFunctions .basicaUthentication (" user "،" password ") .filter ((clientRequest ، next) -> {logger.info (" request: {} {} "، clientRequest.method () القيم) -> القيم. 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 () // يمكن أيضًا وضع معلمات متعددة مباشرة في الخريطة ، ويتوافق اسم المعلمة مع النائب. النائب. 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"). "اختبار") .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) .body. .retRieve (). Bodytomono (String.Class) ؛ logger.info ("النتيجة: {}" ، resp.block ()) ؛ }بعد JSON
استخدم الفاصوليا للنشر
كتاب فئة ثابتة {اسم السلسلة ؛ عنوان السلسلة ؛ السلسلة العامة getName () {return name ؛ } public void setName (اسم السلسلة) {this.name = name ؛ } السلسلة العامة getTitle () {return title ؛ } public void settitle (tring title) {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") .ContentType (mediaType.application_json_utf8) .body (mono.just (book) ، book.class) .retive (). logger.info ("النتيجة: {}" ، resp.block ()) ؛ } مباشرة ما بعد json Raw json
Test public void testpostrawjson () {mono <string> resp = webclient.create (). post () .uri ("http: // localhost: 8080/demo/json") .ContentType (mediaType.application_JSON_UTF8). العنوان/"،/n" + "/" uptor/":/" هذا هو المؤلف/"/n" + "}")) .retrieve (). bodytomono (string.class) ؛ logger.info ("النتيجة: {}" ، resp.block ()) ؛ }Post Binary-Upload File
test public void testuploadfile () {httpheaders headers = new httpheaders () ؛ headers.setContentType (mediaType.image_png) ؛ httpentity <ClassPathResource> intity = new httpentity <> (classPathResource جديد ("parallel.png") ، الرؤوس) ؛ multivalueMap <string ، object> parts = new LinkedMultivalueMap <> () ؛ parts.add ("ملف" ، كيان) ؛ mono <string> resp = webclient.create (). post () .uri ("http: // localhost: 8080/upload") .ContentType (mediaType.multipart_form_data) .body (bodyinserters.frommultipartdata (parts)) .retrive (). logger.info ("النتيجة: {}" ، resp.block ()) ؛ }تنزيل ثنائي
قم بتنزيل الصورة
Test public void testDownloadImage () يلقي ioException {mono <sropress> resp = webclient.create (). get () .uri ( .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 (). clientResponse استجابة = resp.block () ؛ سلسلة التخلص = reponse.headers (). Ashttpheaders (). getFirst (httpheaders.content_disposition) ؛ اسم ملف السلسلة = التصرف. Resource Resource = response.bodyTomono (Resource.class) .block () ؛ ملف Out = ملف جديد (اسم الملف) ؛ fileUtils.copyInputStreamTofile (Resource.getInputStream () ، out) ؛ logger.info (out.getabsolutepath ()) ؛ }معالجة الخطأ
Test public void testretRieve4xx () {webClient webClient = webClient.builder () .baseurl ("https://api.github.com") .Defaultheader (httpheaders.content_type ، "application/vnd.github.v3+json") .DefaulTheader (httpheaders.user_agent ، "Spring 5 WebClient") .Build () ؛ webclient.responsespec responsespec = webclient.method (httpmethod.get) .uri ("/user/repos؟ sort = {sortfield} & direction = {sortdirection}" ، "updated" ، "nevc") .retrieve () ؛ mono <string> mono = reviePec .Onstatus (e -> + ":" + resp.statuscode (). getReasonPhrase ())) ؛ RunTimeException (err.getMessage ()) ؛ النتيجة سلسلة = mono.block () ؛ logger.info ("النتيجة: {}" ، نتيجة) ؛ }ملخص
WebClient هو جيل جديد من قالب REST ASYNC ، و API بسيط نسبيًا وتفاعليًا ، وهو أمر يستحق استخدامه.
ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.