RESTインターフェイスの設計では、インターフェイステストにRESTTEMPLATEを使用することは一般的な方法ですが、使用中は多数の方法とパラメーターのため、多くの学生はフォームの提出とペイロード提出方法の違いを混乱させています。さらに、インターフェイス設計は、従来のブラウザが使用する送信方法とは異なります。 405エラーなど、さまざまなエラーが発生することがよくあります。または、提出されたデータはまったく取得できません。エラーサンプルは次のとおりです。
スレッド「Main」org.springframework.web.client.httpclienterrorexceptionの例外:405メソッドは許可されていません
atorg.springframework.web.client.defaultresponseerrorhandler.handleerror(defaultresponseerrorhandler.java:63)
atorg.springframework.web.client.resttemplate.handleresponse(resttemplate.java:700)
atorg.springframework.web.client.resttemplate.doexecute(repttemplate.java:653)
atorg.springframework.web.client.resttemplate.execute(resttemplate.java:613)
atorg.springframework.web.client.resttemplate.exchange(resttemplate.java:531)
1. Exchangeメソッドを使用して送信します
Exchangeは両方のPOSTメソッドを実行して取得できるため、最も広く使用されており、使用法は次のとおりです。
string url = "http:// localhost/mirana-ee/app/login"; resttemplate client = new rettemplate(); httpheaders headers = new httpheaders(); //この提出方法を簡単に変更しないでください。ほとんどの場合、提出方法はフォーム送信ヘッダーです。SetContentType(Mediatype.Application_Form_urlencoded); params.add( "username"、 "username"); params.add( "password"、 "123456"); httpentity <multivaluemap <string、string >> requestentity = new httpentity <multivaluemap <multivaluemap <multivaluemap <multivaluemap <string、string >>(params、headers); httpmethod.post、requestentity、string.class); // output result system.out.println(respons.getBody());
2。ポストフォレンティティで送信します
ポストフォレンティティは交換の単純化であり、次のように、httpmethod.postパラメーターの削減のみを必要とします。
//上記のコードは正確に同じです
3。フォームの提出とペイロード提出の違いについて
コントローラーメソッドパラメーターでは、「@modelattribute」を「@requestbody」アノテーションに変更すると、この時点での提出方法はペイロード方法です。コードの例は次のとおりです。
// @RequestBodyAnnotation @RequestMapping(value = "/login"、method = requestmethod.post、constupptions = "application/json")// @modelattributeを追加することはありません。 日付());アカウントを返す;}
もう一度、「@modelattribute」を再度追加しないでください。優先度が比較的高いため、システムはフォームを使用して提出されたコンテンツを解析します。
ペイロード方法の場合、提出されたコンテンツは文字列でなければならず、ヘッダーは「アプリケーション/JSON」に設定する必要があります。例は次のとおりです。
//アドレス文字列url = "http:// localhost/mirana-ee/app/login"; resttemplate client = new Resttemplate(); // headerhttpheaders headers = new httheaders(); headers.setContentType(Mediatype.Application_json_json_json_utf8); best to get ObjectMapperObjectMapper mapper through bean injection = new ObjectMapper();Map<String, String> params= Maps.newHashMap();params.put("username", "Inter");params.put("password", "123456");String value = mapper.writeValueAsString(params);HttpEntity<String> requestEntity = new httpentity <string>(value、headers); // http request respessentity <string> response> response = client.postforentity(url、requestentity、string.class); system.out.println(respons.getBody());コンテンツが文字列モードで送信されない場合、次のエラーが間違いなく表示されます。
スレッド「Main」org.springframework.web.client.httpclienterrorexceptionの例外:400悪いリクエスト
atorg.springframework.web.client.defaultresponseerrorhandler.handleerror(defaultresponseerrorhandler.java:63)
atorg.springframework.web.client.resttemplate.handleresponse(resttemplate.java:700)
atorg.springframework.web.client.resttemplate.doexecute(repttemplate.java:653)
atorg.springframework.web.client.resttemplate.execute(resttemplate.java:613)
atorg.springframework.web.client.resttemplate.postforentity(repttemplate.java:407)
最後に、要求パラメーターは@RequestBodyを介して取得できないことを強調する必要があります。上記のサーバーのコードが次の形式に変更された場合、データは間違いなく取得されませんが、フォームの提出には逆のことが当てはまります。
@RequestMapping(value = "/login"、consumers = "application/json"、method = requestmethod.post)publicアカウントgetAccount(@requestbodyアカウント、httpservletrequest request){//パラメーター値system.out.out.println(request.getparameter( "username"); account.setversion(new date());アカウントを返す;}4。httpentityの構造
HTTPentityは、HTTP要求のカプセル化であり、ヘッダーとボディの2つの部分を含む。ヘッダーはリクエストヘッダーを設定するために使用され、ボディはリクエストボディを設定するために使用されるため、そのコンストラクターは次のとおりです。
//値はリクエストbody //ヘッダーはリクエストヘッダーhttpentity <string> requestentity = new httpentity <string>(value、headers);
5。Httpentityとurivariables
RestTemplateの使用では、HTTPentityを使用して特定のパラメーター値を渡しますが、Urivariablesはアドレスパラメーターの代わりにHTTPアドレスをフォーマットするために使用されます。正しい使用法は次のとおりです。
//パラメーターのフォーマットパラメーターの追加url = "http:// localhost/mirana-ee/app/{path}"; // prepare formattingパラメーターMap <string、string> varparams = maps.newhashmap(); varparams.put( "path"、 "path"、 "login"); client.postforentity(url、requestentity、string.class、varparams);6。httpmessageconverterに関するメモ
オンラインの多くの例では、多くの人がペイロード提出を処理するためにカスタムhttpmessageconverterを追加していることがわかりました。
// client.getMessageConverters()には必要ありません。Add(new MappingJackson2HTTPMESSAGECONVERTER()); client.getMessageConverters()。add(new Stringhttpmessageconverter());
次に、ソースコードをチェックしてデバッグした後、RestTemplateには次のように7種類のhttpmessageConvertersが組み込まれていることがわかりました。
1。org.springframework.http.converter.bytearrayhttpmessageconverter
2。org.springframework.http.converter.stringhttpmessageconverter
3。org.springframework.http.converter.resourcehttpmessageconverter
4。org.springframework.http.converter.xml.sourcehttpmessageconverter
5。ORG.SPRINGFRAMEWORK.HTTP.CONVERTER.SUPPORT.ALLENCOMPASSINGFORMHTTPMESSAGECONVERTER
6。org.springframework.http.converter.xml.jaxb2rootelementhttpmessageconverter
7。org.springframework.http.converter.json.mappingjackson2httpmessageconverter
「 `
結論は
RESTTEMPLATEは、フォームデータの送信の難しさを大幅に簡素化でき、JSONデータを自動的に変換する機能が付属しています。ただし、httpentity(ヘッダーとボディ)の構成構造を理解し、urivariablesとの違いを理解することによってのみ、その使用法を本当に理解できます。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。