レコードは主に使用の便宜のためのものであり、完全ではないかもしれませんが、基本的には直接使用できます
hutool の HttpUtil でパッケージ化された jar パッケージを直接使用できます
例えば:
get リクエストを使用する
文字列 url ="https://www.baidu.com";
HttpUtil.get(URL);
get メソッドを使用する場合は、タイムアウト期間を設定したり、マップに入れたり、ボディに入れたりなど、必要に応じて構成できます。
get の後にブラケットに直接挿入できます。
ポストメソッドを使用する
HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result= HttpUtil.post("https://www.baidu.com", paramMap);
RestTemplate の使用は単純で大雑把です。
restTemplate 偽造防止マークの restful インターフェイスを使用するのは非常に簡単です. 以下に簡単な例を示します:
//リクエストアドレス
文字列 url = "http://localhost:8080/testHelloWorld";
//入参
マップ map=new HashMap();
map("こんにちは",aa);
RestTemplate restTemplate=新しい RestTemplate
ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,map, String.class)
このうち、restTemplate で渡される 3 つのパラメータは、リクエスト アドレス、リクエスト パラメータ、および HTTP レスポンス変換に変換されたオブジェクト タイプであり、返されるタイプは、postForEntity で使用されるメソッドに応じて変更できます。
POST リクエスト
POSTForObject メソッドを呼び出す、postForEntity メソッドを使用する、exchange メソッドを使用する
postForObject メソッドと postForEntity メソッドの違いは、postForEntity メソッドでヘッダー属性を設定できることで、ヘッダー属性値を指定する必要がある場合は、postForEntity メソッドを使用します。exchange メソッドは postForEntity に似ていますが、より柔軟であり、exchange は get 要求を呼び出すこともできます。
private static void createTest(){ final String uri = "http://localhost:8080/test"; TestVO newEmployee = new TestVO(-1, "aa", "ming", "[email protected]"); RestTemplate restTemplate = new RestTemplate(); TestVO 結果 = restTemplate.postForObject( uri, newTest, TestVO.class); System.out.println(結果); }
リクエストを取得
private static void getTest(){ final String uri = "http://localhost:8080/test"; RestTemplate restTemplate = new RestTemplate(); 文字列の結果 = restTemplate.getForObject(uri, String.class); System.out.println(結果); }
RestTemplate 構成クラス
@Configuration//このアノテーションにより、Spring でスキャン可能 public class RestTemplateConfig implements WebMvcConfigurer { /** * RestTemplate オブジェクトを作成し、RestTemplate オブジェクトのライフサイクル管理を Spring に引き渡す */ @Bean public RestTemplate restTemplate() { // RestTemplate restTemplate = new RestTemplate(); // 中国語の文字化けを設定する方法 1 // restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(Charset.forName("UTF-8"))); //中国語の文字化けを設定する 問題 2 // restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 中国語のエンコーディングをサポート return new RestTemplate(); } }