RestTemplateの使用の例を書きました。 Spring 5はReactiveを完全に導入し、RestTemplateのWebClientのリアクティブバージョンも持っているため、この記事ではWebClientの基本的な使用を示します。
ヘッダーをキャリーするようリクエストします
クッキーをキャリーします
@test public void testwithcookie(){mono <string> resp = webclient.create().method(httpmethod.get).uri( "http://baidu.com").cookie( "token"、 "xxxx").cookie( "jsessionid"、 "xxxx")。 .bodytomono(string.class); logger.info( "result:{}"、resp.block()); }基本的な認証を運ぶ
@test public void testwithbasicauth(){string basicauth = "basic"+ base64.getEncoder()。encodetostring( "user:pwd" .getbytes(stardingcharsets.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( "result:{}"、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、khtml、ygeco) Chrome/63.0.3239.132 Safari/537.36 ").Filter(ExchangeFilterFunctions .Basicauthentication(" user "、" password ")).filter((clientRequest、next) - > {logger.info(" request:{}} {} "、client request.method(); clientRequest.headers().foreach((name、values) - > foreach(value-> logger.info( "{} = {}"、name、value)); mono <string> resp = webclient.get().uri( "https://baidu.com").retrieve().bodytomono(string.class); logger.info( "result:{}"、resp.block()); }リクエストを取得します
プレースホルダーを使用してパスパラメーターを渡します
@test public void testurlplaceholder(){mono <string> resp = webclient.create().get()//複数のパラメーターもマップに直接配置することができ、パラメーター名はplaceholder.uri( "http://www.baidu.com/s? Placeholder.retrieve().bodytomono(string.class); logger.info( "result:{}"、resp.block()); } uribuilderを使用してパラメーターを渡します
@test public void testurlbiulder(){mono <string> resp = webclient.create().uri(uribuilder-> uribuilder .scheme( "http").host( "www.baidu.com")。 "test").build()).retrieve().bodytomono(string.class); logger.info( "result:{}"、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( "result:{}"、resp.block()); }ポストJSON
豆を使用して投稿してください
静的クラスブック{文字列名;文字列タイトル; public string getName(){return name; } public void setName(string name){this.name = name; } public string getTitle(){return title; } public void settitle(string title){this.title = title; }} @test public void testpostjson(){book book = new book(); book.setname( "name"); 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)。 logger.info( "result:{}"、resp.block()); } RAW JSONを直接投稿します
@test public void testpostrawjson(){mono <string> resp = webclient.create()。post().uri( "http:// localhost:8080/demo/json").contenttype(mediatype.application_json_utf8)。 is title/"、/n" + "/" Author/":/"これは著者/"/n" + "}")。retrieve()。bodytomono(string.class); logger.info( "result:{}"、resp.block()); }バイナリアプロードファイルを投稿します
@test public void testuploadfile(){httpheaders headers = new httpheaders(); headers.setContentType(mediatype.image_png); httpentity <ClassPathResource> entity = new httpentity <>(new ClassPathResource( "Parallel.png")、Headers); MultivalUeMap <String、object> parts = new LinkedMultivalueMap <>(); parts.add( "file"、entity); mono <string> resp = webclient.create()。post().uri( "http:// localhost:8080/upload").contenttype(mediatype.multipart_form_data).body(bodyinserters.frommultipartdata(parts)).retriemo()。 logger.info( "result:{}"、resp.block()); }バイナリをダウンロードします
写真をダウンロードしてください
@test public void testdownloadimage()throws ioexception {mono <resource> resp = webclient.create()。 .retrieve()。bodytomono(resource.class);リソースリソース= resp.block(); bufferedimage bufferedimage = imageio.read(resource.getInputStream()); Imageio.write(bufferedimage、 "png"、new file( "captcha.png")); }ファイルをダウンロードします
@test public void testdownloadfile()throws ioexception {mono <clientresponse> resp = webclient.create()。get().uri( "http:// localhost:8080/file/download").accept(mediatype.application_octet_stream).exchange(); clientResponse応答= resp.block(); string dision = response.headers()。ashttpheaders()。getfirst(httpheaders.content_disposition); string fileName = disoge.substring(disoge.indexof( "=")+1);リソースリソース= response.bodytomono(resource.class).block(); file out = new File(filename); 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"、 "desc").retrieve(); Mono <String> Mono = ResponseSpec .OnStatus(e-> e.is4xxclienterror()、resp-> {logger.error( "error:{}、msg:{}"、resp.statuscode()。value()、resp.statuscode()。 runtimeexception(resp.statuscode()。value() + ":" + rep.statuscode()ステータス:{}、msg:{} "、err.getRawStatusCode()、err.getResponseBodyAsstring());新しいruntimexcection(err.getMessage());}).Onerrorreturn(" Fallback ");文字列結果= mono.block(); logger.info( "result:{}"、result); }まとめ
WebClientは新世代のAsync RESTテンプレートであり、APIは比較的シンプルで反応的であり、使用する価値があります。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。