0

RESTfull Web サービス リソースを呼び出そうとしています。このリソースはサード パーティによって提供されており、リソースは OPTIONS http 動詞で公開されています。

サービスと統合するには、プロバイダーによって身元が特定された特定の本文を含むリクエストを送信する必要がありますが、それを実行すると、不適切なリクエストが返されました。その後、コードをトレースすると、以下のコードに基づいて、リクエストの本文が残りのテンプレートによって無視されることがわかりました。

if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) ||
            "PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) {
        connection.setDoOutput(true);
    }
    else {
        connection.setDoOutput(false);
    }

私の質問ですが、この動作をオーバーライドする標準的な方法はありますか、それとも別のツールを使用する必要がありますか?

4

1 に答える 1

1

貼り付けたコードは

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();
    }
}

}

于 2016-10-07T20:48:03.417 に答える