0

RESTfull 웹 서비스 리소스를 호출하려고하는데이 리소스는 제 3 자에 의해 제공되며 리소스는 OPTIONS http 동사와 함께 노출됩니다.스프링 휴식 템플릿을 사용하여 본문과 함께 HTTP OPTIONS 요청을 보내는 방법은 무엇입니까?

서비스와 통합하려면 특정 본문을 가진 요청을 제공자에게 보내야합니다.이 요청은 제공자가 ID를 요청하지만 잘못된 요청을 받았을 때 나타납니다. 그 후 나는 다음 내 코드를 추적 제가 요청의 본문은 아래의 코드를 기반으로 나머지 템플릿에 의해 무시됩니다 인식 :

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

내 질문에,이 동작을 재정의하는 표준 방법이 아니면 다른를 사용한다 수단?

답변

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

}

(봄 부팅 (@RunWith (SpringRunner.class) @SpringBootTest를 사용하여 작동이 공장

new RestTemplate(new SimpleClientHttpRequestWithGetBodyFactory()); 

솔루션을 증명하기 위해 테스트를 기반으로 새 RestTemplate 만들기 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(); 
    } 
} 

}

+0

httpMethod = OPTIONS의 connection.setDoOutput (true)과 동일한 파생 SimpleClientHttpRequestWithGetBodyFactory를 다시 테스트했습니다. 나머지 템플릿이 던지고 있습니다 : org.springframework.web.client.ResourceAccessException : "http : // localhost : 18181/test"에 대한 OPTIONS 요청의 I/O 오류 : HTTP 메소드 OPTIONS가 출력을 지원하지 않습니다. 상자가 된 예외는 java.net.ProtocolException : HTTP 메소드 OPTIONS가 출력을 지원하지 않습니다. 이것이 Options에 connection.setDoOutput (false)이있는 이유입니다. –

관련 문제