您粘贴的代码来自
SimpleClientHttpRequestFactory.prepareConnection(HttpURLConnection connection, String httpMethod)
我知道是因为我已经在几个小时前调试了该代码。我必须使用restTemplate 对body 进行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());
证明解决方案正在使用 spring boot 的测试 (@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();
}
}
}