基本概念
Spring Restemplateは、RESTサービスにアクセスするためにSpringが提供するクライアントです。 RestTemplateは、リモートHTTPサービスへのさまざまな便利なアクセスを提供します。これにより、クライアントのライティング効率が大幅に向上できます。したがって、Androidやサードパーティのサービスプロバイダーなどの多くのクライアントは、RestTemplateを使用してRestfulサービスを要求します。
Spring-WebのRestemplataは、Javaの基礎となるHTTPのカプセル化です。 RestTemplataを使用しているユーザーは、基礎となる接続の確立に注意を払うことができなくなりました。 RESTTEMPLATAは、REST仕様をサポートするだけでなく、Return Valueオブジェクトタイプも定義します。
使用中は、RestTemplateオブジェクトを直接新しいものにできます。作成したRESTTEMPLATEオブジェクトにメッセージを返すメッセージコンバーターがあります。返されたデータのmediatypeに基づいて対応するコンバーターを見つけることができ、mediatype変換を実行できます。また、自分でメッセージコンバーターを作成したり、AbstractGenerichttpmessageConverter <T>クラスを継承したり、httpmessageConverter <T>インターフェイスを実装したりするクラスを作成します。 CanReadメソッドとCanWriteメソッドは、自分で審査し、Write -InternalまたはWriteメソッドのストリームにパラメーターを書き込み、ReadInternalまたは読み取り方法とタイプマップでストリームの本体から返された結果を取得する必要があることに注意してください。
RESTTEMPLATEオブジェクトは、java.netパッケージの下の実装を使用して、下部にHTTPリクエストを作成します。 ClientHTTPRequestFactoryを使用して、さまざまなHTTP要求方法を指定できます。
clienthttprequestFactoryインターフェイスは、主に2つの実装方法を提供します。
RestTemplateは、デフォルトでSimpleClientHTTPRequestFactoryを使用し、内部的にhttpConnectionを呼び出してJDKを呼び出します。デフォルトのタイムアウトは-1です。タイムアウトを自分で定義できます。
simpleclienthttprequestfactory factory = new simpleclienthttprequestfactory(); //接続タイムアウト、ユニットミリ秒ファクトリーを設定します。 RESTTEMPLATE RESTTEMPLATE = new RestTemplate(Factory);
get requestsを使用してください:
string url = "http:// localhost:80/mandy/login.json?account = 123456&password = 123456"; ress res = rettemplate.getforobject(url、result.class);
RESTTEMPLATEソースコード:
@Override public <t> t getForObject(String URL、class <t> responsetype、object ... urlvariables)shows restclientexception {requestCallback requestCallback = acceptheaderRequestCallback(respondetype); httpmessageconverterextractor <t> responsextractor = new httpmessageconverterextractor <t>(responsetype、getmessageconverters()、logger); return execute(url、httpmethod.get、requestcallback、responsextractor、urlvariables); }GETリクエストを使用して、パラメーターをアドレスに直接スプライスするのが最善です。理由がわからない。 3番目のパラメーターを使用する場合、MultivalueMapタイプでさえ機能しません(インターネット上の一部の人は、MultivalueMapタイプを使用することは問題ないと言いますが、試しましたが、うまくいきません)
投稿リクエストを使用してください:
hashmap <string、object> map = new hashmap <string、object>(); map.put( "name"、 "test"); map.put( "account"、 "qwer"); map.put( "password"、 "qwer"); ObjectMapper mapper = new objectMapper();文字列jsonstr = null; try {jsonstr = mapper.writevalueasstring(map); } catch(Exception e){e.printstacktrace(); } // httpヘッダーエンティティを作成し、データ形式などのヘッダー情報を入力しますhttpheaders httpheaders = new httpheaders(); httpheaders.setContentType(mediatype.application_json_utf8); // httpエンティティを作成するには、コンストラクターを直接使用してリクエストボディとリクエストヘッダーをhttpentity <string> httpentity = new httpentity <string>(jsonstr2、httpheaders); "http:// localhost:80/mandy/user_enable.json"; // res2 = rettemplate.postforobject(url、httpentity、result.class)を要求するメソッドを呼び出すRESTTEMPLATEソースコード:
@Override public <t> t postforobject(string url、object request、class <t> responsetype、object ... urivariables)rets clientexception {requestcallback requestcallback = httpentitycallback(request、respondetype); httpmessageconverterextractor <t> responsextractor = new httpmessageconverterextractor <t>(responsetype、getmessageconverters()、logger); return execute(url、httpmethod.post、requestcallback、responsextractor、urivariables); }プットリクエストを使用してください:
hashmap <string、object> map = new hashmap <string、object>(); map.put( "user_id"、 "1"); map.put( "enable"、0); objectmapper mapper = new objectmapper(); string jsonstr = null; try {jsonstr = mapper.writevalueasscoption(map); e.printstacktrace();} // httpヘッダーエンティティを作成し、データ形式httpheaders httpheaders = new httpheaders(); httpheaders.setContentType(mediatype.application_json_utf8); httpentity <string> httpentity = new httpentity <string>(jsonst、httpheaders); string url = "http:// localhost:80/mandy/user_enable.json"; retttemplate.put(url、httpentity);RESTTEMPLATEソースコード:
@Override public void put(string url、object request、object ... urlvariables)shrows restclientexception {requestcallback requestcallback = httpentitycallback(request); execute(url、httpmethod.put、requestcallback、null、urlvariables); }この方法のわずかな欠点は、リクエスト結果の返品値がないことです。返品値を使用する必要がある場合は、この方法を使用できません。
削除タイプリクエストを使用する場合、rettemplateのputメソッドのパラメーター列に次の型のみがあります
@overridepublic void delete(string url、object ... urlvariables)restclientexception {execute(url、httpmethod.delete、null、null、urlvariables);}@overridepublic void delete(string url、map <string、? httpmethod.delete、null、null、urlvariables);}@overridepublic void delete(uri url)throws restclientexception {execute(url、httpmethod.delete、null、null);}}これらのメソッドはパラメーターを提供せず、リクエストボディのコンテンツを配置してください。したがって、RestTemplateが提供する削除メソッドを直接使用する場合は、インターフェイスはRestful Styleを使用し、アドレスにパラメーターを配置し、 @pathvariable(value = "")注釈を介してパラメーターを取得する必要があります。
キーポイント:実際、次のように、レストテンプレートの交換方法を直接使用できます
@OverridePublic <T> ResponseNtity <T> Exchange(String URL、HTTPMETHODメソッド、HTTPENTITY <? ResponseExtractor <ResponseNtity <T >> ResponseExtractor = ResponseNtityExtractor(ResponseType); return execute(url、method、requestcallback、responsextractor、urivariables);}
ここでは、1つのメソッドのみをリストします。その他はソースコードに記載されています。この方法は、あらゆる種類のリクエストを行うことができます。
この方法では、メソッドパラメーターはhttpmethod列挙で取得できます。 RequestEntityパラメーターは、リクエスト本体とリクエストヘッダーなど、それ自体でカプセル化されたHTTPENTITYエンティティです。 ResponseTypeパラメーターは、結果を返すマッピングクラスです。 urivariablesパラメーターは、それが役に立たないという印象を与えてくれます(個人的な意見)。リクエストリターンインターフェイスへのアクセスは、メソッドリターン値のgetBody()メソッドを介して取得できます。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。