貼り付けたコードは
SimpleClientHttpRequestFactory.prepareConnection(HttpURLConnection connection, String httpMethod)
私は数時間前にそのコードをデバッグしたので知っています。restTemplate を使用して本文で HTTP GET を実行する必要がありました。そのため、SimpleClientHttpRequestFactory を拡張し、prepareConnection をオーバーライドして、新しいファクトリを使用して新しい RestTemplate を作成しました。
public class SimpleClientHttpRequestWithGetBodyFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
if ("GET".equals(httpMethod)) {
connection.setDoOutput(true);
}
}
}
このファクトリに基づいて新しい RestTemplate を作成します
new RestTemplate(new SimpleClientHttpRequestWithGetBodyFactory());
スプリング ブートを使用してソリューションが機能していることを証明するテスト (@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT))
public class TestRestTemplateTests extends AbstractIntegrationTests {
@Test
public void testMethod() {
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestWithBodyForGetFactory());
HttpEntity<String> requestEntity = new HttpEntity<>("expected body");
ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:18181/test", HttpMethod.GET, requestEntity, String.class);
assertThat(responseEntity.getBody()).isEqualTo(requestEntity.getBody());
}
@Controller("/test")
static class TestController {
@RequestMapping
public @ResponseBody String testMethod(HttpServletRequest request) throws IOException {
return request.getReader().readLine();
}
}
}