カスタム ヘッダーとクエリ パラメータを含む呼び出しを行う必要があります。ヘッダーのみ (本文なし) をREST
設定し、メソッドを次のように使用します。HttpEntity
RestTemplate.exchange()
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
Map<String, String> params = new HashMap<String, String>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);
HttpEntity entity = new HttpEntity(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);
これはクライアント側で失敗し、dispatcher servlet
リクエストをハンドラーに解決できません。デバッグしたところ、リクエスト パラメータが送信されていないようです。
リクエスト本文を使用し、クエリパラメータなしで交換を行うと、POST
正常に動作します。
誰か何かアイデアはありますか?
ベストアンサー1
URL /パス /パラメータなどを簡単に操作するには、SpringのURIコンポーネントビルダークラスを使用して、パラメータのプレースホルダを含む URL テンプレートを作成し、呼び出し時にそれらのパラメータの値を指定しますRestOperations.exchange(...)
。手動で文字列を連結するよりも簡潔で、URL エンコードも自動的に行われます。
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
HttpEntity<?> entity = new HttpEntity<>(headers);
String urlTemplate = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("msisdn", "{msisdn}")
.queryParam("email", "{email}")
.queryParam("clientVersion", "{clientVersion}")
.queryParam("clientType", "{clientType}")
.queryParam("issuerName", "{issuerName}")
.queryParam("applicationName", "{applicationName}")
.encode()
.toUriString();
Map<String, ?> params = new HashMap<>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);
HttpEntity<String> response = restOperations.exchange(
urlTemplate,
HttpMethod.GET,
entity,
String.class,
params
);