Here are the examples of the java api org.springframework.http.client.ClientHttpRequest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
61 Examples
19
View Source File : RootUriRequestExpectationManager.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private ClientHttpRequest replaceURI(ClientHttpRequest request, String replacementUri) {
URI uri;
try {
uri = new URI(replacementUri);
if (request instanceof MockClientHttpRequest) {
((MockClientHttpRequest) request).setURI(uri);
return request;
}
return new ReplaceUriClientHttpRequest(uri, request);
} catch (URISyntaxException ex) {
throw new IllegalStateException(ex);
}
}
19
View Source File : RootUriRequestExpectationManager.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Override
public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
String uri = request.getURI().toString();
if (uri.startsWith(this.rootUri)) {
request = replaceURI(request, uri.substring(this.rootUri.length()));
}
try {
return this.expectationManager.validateRequest(request);
} catch (replacedertionError ex) {
String message = ex.getMessage();
String prefix = "Request URI expected:</";
if (message != null && message.startsWith(prefix)) {
throw new replacedertionError("Request URI expected:<" + this.rootUri + message.substring(prefix.length() - 1));
}
throw ex;
}
}
19
View Source File : DelayedLiveReloadTriggerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
/**
* Tests for {@link DelayedLiveReloadTrigger}.
*
* @author Phillip Webb
*/
public clreplaced DelayedLiveReloadTriggerTests {
private static final String URL = "http://localhost:8080";
@Mock
private OptionalLiveReloadServer liveReloadServer;
@Mock
private ClientHttpRequestFactory requestFactory;
@Mock
private ClientHttpRequest errorRequest;
@Mock
private ClientHttpRequest okRequest;
@Mock
private ClientHttpResponse errorResponse;
@Mock
private ClientHttpResponse okResponse;
private DelayedLiveReloadTrigger trigger;
@Before
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
given(this.errorRequest.execute()).willReturn(this.errorResponse);
given(this.okRequest.execute()).willReturn(this.okResponse);
given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR);
given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK);
this.trigger = new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, URL);
}
@Test
public void liveReloadServerMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)).withMessageContaining("LiveReloadServer must not be null");
}
@Test
public void requestFactoryMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)).withMessageContaining("RequestFactory must not be null");
}
@Test
public void urlMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)).withMessageContaining("URL must not be empty");
}
@Test
public void urlMustNotBeEmpty() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")).withMessageContaining("URL must not be empty");
}
@Test
public void triggerReloadOnStatus() throws Exception {
given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()).willReturn(this.errorRequest, this.okRequest);
long startTime = System.currentTimeMillis();
this.trigger.setTimings(10, 200, 30000);
this.trigger.run();
replacedertThat(System.currentTimeMillis() - startTime).isGreaterThan(300L);
verify(this.liveReloadServer).triggerReload();
}
@Test
public void timeout() throws Exception {
given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException());
this.trigger.setTimings(10, 0, 10);
this.trigger.run();
verify(this.liveReloadServer, never()).triggerReload();
}
}
19
View Source File : DelayedLiveReloadTrigger.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private boolean isUp() {
try {
ClientHttpRequest request = createRequest();
ClientHttpResponse response = request.execute();
return response.getStatusCode() == HttpStatus.OK;
} catch (Exception ex) {
return false;
}
}
19
View Source File : ServletWebServerMvcIntegrationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
private void doTest(AnnotationConfigServletWebServerApplicationContext context, String resourcePath) throws Exception {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI("http://localhost:" + context.getWebServer().getPort() + resourcePath), HttpMethod.GET);
try (ClientHttpResponse response = request.execute()) {
String actual = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
replacedertThat(actual).isEqualTo("Hello World");
}
}
19
View Source File : CreateRequestInterceptor.java
License : Apache License 2.0
Project Creator : yametech
License : Apache License 2.0
Project Creator : yametech
@Override
public Object after(Object thisObj, Object[] allArguments, Method method, Object ret, Throwable t, BeforeResult<SpanInfo> beforeResult) {
Span span = tracer.currentSpan();
if (span == null) {
return ret;
}
ClientHttpRequest clientHttpRequest = (ClientHttpRequest) ret;
if (clientHttpRequest instanceof AbstractClientHttpRequest) {
AbstractClientHttpRequest httpRequest = (AbstractClientHttpRequest) clientHttpRequest;
injector.inject(span.context(), httpRequest.getHeaders());
}
return ret;
}
19
View Source File : UserJwtSsoTokenRestTemplate.java
License : Apache License 2.0
Project Creator : WeBankPartners
License : Apache License 2.0
Project Creator : WeBankPartners
@Override
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest req = super.createRequest(url, method);
AuthenticatedUser loginUser = AuthenticationContextHolder.getCurrentUser();
if (loginUser != null && StringUtils.isNotBlank(loginUser.getToken())) {
if (log.isDebugEnabled()) {
log.debug("request {} with access token:{}", url.toString(), loginUser.getToken());
}
req.getHeaders().add(HttpHeaders.AUTHORIZATION, loginUser.getToken());
}
return req;
}
19
View Source File : BasicAuthorizationInterceptorTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void interceptShouldAddHeader() throws Exception {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.clreplaced);
byte[] body = new byte[] {};
new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body, execution);
verify(execution).execute(request, body);
replacedertEquals("Basic c3ByaW5nOmJvb3Q=", request.getHeaders().getFirst("Authorization"));
}
19
View Source File : HttpAccessor.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Create a new {@link ClientHttpRequest} via this template's {@link ClientHttpRequestFactory}.
* @param url the URL to connect to
* @param method the HTTP method to execute (GET, POST, etc)
* @return the created request
* @throws IOException in case of I/O errors
* @see #getRequestFactory()
* @see ClientHttpRequestFactory#createRequest(URI, HttpMethod)
*/
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest request = getRequestFactory().createRequest(url, method);
if (logger.isDebugEnabled()) {
logger.debug("HTTP " + method.name() + " " + url);
}
return request;
}
19
View Source File : UnorderedRequestExpectationManager.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public RequestExpectation matchRequest(ClientHttpRequest request) throws IOException {
RequestExpectation expectation = this.remainingExpectations.findExpectation(request);
if (expectation == null) {
throw createUnexpectedRequestError(request);
}
this.remainingExpectations.update(expectation);
return expectation;
}
19
View Source File : SimpleRequestExpectationManager.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
protected RequestExpectation matchRequest(ClientHttpRequest request) throws IOException {
RequestExpectation expectation = this.repeatExpectations.findExpectation(request);
if (expectation == null) {
if (this.expectationIterator == null || !this.expectationIterator.hasNext()) {
throw createUnexpectedRequestError(request);
}
expectation = this.expectationIterator.next();
expectation.match(request);
}
this.repeatExpectations.update(expectation);
return expectation;
}
19
View Source File : DefaultResponseCreator.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public ClientHttpResponse createResponse(@Nullable ClientHttpRequest request) throws IOException {
MockClientHttpResponse response;
if (this.contentResource != null) {
InputStream stream = this.contentResource.getInputStream();
response = new MockClientHttpResponse(stream, this.statusCode);
} else {
response = new MockClientHttpResponse(this.content, this.statusCode);
}
response.getHeaders().putAll(this.headers);
return response;
}
19
View Source File : MockRestRequestMatchers.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private static MultiValueMap<String, String> getQueryParams(ClientHttpRequest request) {
return UriComponentsBuilder.fromUri(request.getURI()).build().getQueryParams();
}
19
View Source File : DefaultRequestExpectation.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Note that as of 5.0.3, the creation of the response, which may block
* intentionally, is separated from request count tracking, and this
* method no longer increments the count transparently. Instead
* {@link #incrementAndValidate()} must be invoked independently.
*/
@Override
public ClientHttpResponse createResponse(@Nullable ClientHttpRequest request) throws IOException {
ResponseCreator responseCreator = getResponseCreator();
replacedert.state(responseCreator != null, "createResponse() called before ResponseCreator was set");
return responseCreator.createResponse(request);
}
19
View Source File : DefaultRequestExpectation.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public void match(ClientHttpRequest request) throws IOException {
for (RequestMatcher matcher : getRequestMatchers()) {
matcher.match(request);
}
}
19
View Source File : AbstractRequestExpectationManager.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* As of 5.0.3 subclreplacedes should implement this method instead of
* {@link #validateRequestInternal(ClientHttpRequest)} in order to match the
* request to an expectation, leaving the call to create the response as a separate step
* (to be invoked by this clreplaced).
* @param request the current request
* @return the matched expectation with its request count updated via
* {@link RequestExpectation#incrementAndValidate()}.
* @since 5.0.3
*/
protected RequestExpectation matchRequest(ClientHttpRequest request) throws IOException {
throw new UnsupportedOperationException("It looks like neither the deprecated \"validateRequestInternal\"" + "nor its replacement (this method) are implemented.");
}
19
View Source File : AbstractRequestExpectationManager.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Subclreplacedes must implement the actual validation of the request
* matching to declared expectations.
* @deprecated as of 5.0.3, subclreplacedes should implement {@link #matchRequest(ClientHttpRequest)}
* instead and return only the matched expectation, leaving the call to create the response
* as a separate step (to be invoked by this clreplaced).
*/
@Deprecated
@Nullable
protected ClientHttpResponse validateRequestInternal(ClientHttpRequest request) throws IOException {
return null;
}
19
View Source File : DownloadRestTemplate.java
License : MIT License
Project Creator : Toparvion
License : MIT License
Project Creator : Toparvion
@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
replacedert.notNull(url, "'url' must not be null");
replacedert.notNull(method, "'method' must not be null");
ClientHttpResponse response;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
handleResponse(url, method, response);
if (responseExtractor != null) {
return responseExtractor.extractData(response);
} else {
return null;
}
} catch (IOException ex) {
String resource = url.toString();
String query = url.getRawQuery();
resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + resource + "\": " + ex.getMessage(), ex);
}
// Here is the only difference of this method from its parent - we deliberately don't close response input stream
// because we definitely know (1) it wasn't read yet, (2) it will be read later and (3) it will be closed
// immediately after reading (at org.springframework.http.converter.ResourceHttpMessageConverter:139)
// finally {
// if (response != null) {
// response.close();
// }
// }
}
19
View Source File : HttpAccessor.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Create a new {@link ClientHttpRequest} via this template's {@link ClientHttpRequestFactory}.
* @param url the URL to connect to
* @param method the HTTP method to execute (GET, POST, etc)
* @return the created request
* @throws IOException in case of I/O errors
* @see #getRequestFactory()
* @see ClientHttpRequestFactory#createRequest(URI, HttpMethod)
*/
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest request = getRequestFactory().createRequest(url, method);
initialize(request);
if (logger.isDebugEnabled()) {
logger.debug("HTTP " + method.name() + " " + url);
}
return request;
}
19
View Source File : HttpAccessor.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
private void initialize(ClientHttpRequest request) {
this.clientHttpRequestInitializers.forEach(initializer -> initializer.initialize(request));
}
19
View Source File : MockHttpOutputMessageAccess.java
License : Apache License 2.0
Project Creator : openapi4j
License : Apache License 2.0
Project Creator : openapi4j
@Override
public byte[] apply(ClientHttpRequest source) {
if (source instanceof MockHttpOutputMessage) {
return ((MockHttpOutputMessage) source).getBodyAsBytes();
}
return null;
}
19
View Source File : ClientRequest.java
License : Apache License 2.0
Project Creator : openapi4j
License : Apache License 2.0
Project Creator : openapi4j
/**
* Create a request from source.
* If the source is a {@link org.springframework.mock.http.MockHttpOutputMessage}
* or the body is a {@link ByteArrayOutputStream} the body is extracted as {@code byte[]}.
* @param source the request with method, uri and headers and possibly body
* @return the created request
*/
public static Request of(ClientHttpRequest source) throws IOException {
byte[] body = MOCK_HTTP_OUTPUT_MESSAGE_ACCESS.apply(source);
if (body == null && source.getBody() instanceof ByteArrayOutputStream) {
body = ((ByteArrayOutputStream) source.getBody()).toByteArray();
}
return of(source, body);
}
19
View Source File : BasicAuthorizationInterceptorTests.java
License : MIT License
Project Creator : mindcarver
License : MIT License
Project Creator : mindcarver
@Test
public void interceptShouldAddHeader() throws Exception {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.clreplaced);
byte[] body = new byte[] {};
new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body, execution);
verify(execution).execute(request, body);
replacedertEquals("Basic c3ByaW5nOmJvb3Q=", request.getHeaders().getFirst("Authorization"));
}
19
View Source File : HttpAccessor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Create a new {@link ClientHttpRequest} via this template's {@link ClientHttpRequestFactory}.
* @param url the URL to connect to
* @param method the HTTP method to exectute (GET, POST, etc.)
* @return the created request
* @throws IOException in case of I/O errors
*/
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest request = getRequestFactory().createRequest(url, method);
if (logger.isDebugEnabled()) {
logger.debug("Created " + method.name() + " request for \"" + url + "\"");
}
return request;
}
19
View Source File : MockClientHttpRequestFactoryTests.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Test
public void createRequest() throws Exception {
URI uri = new URI("/foo");
ClientHttpRequest expected = (ClientHttpRequest) this.server.expect(anything());
ClientHttpRequest actual = this.factory.createRequest(uri, HttpMethod.GET);
replacedertSame(expected, actual);
replacedertEquals(uri, actual.getURI());
replacedertEquals(HttpMethod.GET, actual.getMethod());
}
19
View Source File : DefaultResponseCreator.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException {
MockClientHttpResponse response;
if (this.contentResource != null) {
InputStream stream = this.contentResource.getInputStream();
response = new MockClientHttpResponse(stream, this.statusCode);
} else {
response = new MockClientHttpResponse(this.content, this.statusCode);
}
response.getHeaders().putAll(this.headers);
return response;
}
19
View Source File : CasAuthorizationInterceptorTest.java
License : MIT License
Project Creator : kakawait
License : MIT License
Project Creator : kakawait
@Test
public void intercept_NullProxyTicket_IllegalStateException() throws IOException {
String service = "http://httpbin.org/get";
ClientHttpRequestExecution clientHttpRequestExecution = mock(ClientHttpRequestExecution.clreplaced);
ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create(service));
when(proxyTicketProvider.getProxyTicket(service)).thenReturn(null);
replacedertThatThrownBy(() -> casAuthorizationInterceptor.intercept(request, null, clientHttpRequestExecution)).isInstanceOf(IllegalStateException.clreplaced).hasMessage(format("Proxy ticket provider returned a null proxy ticket for service %s.", service));
verify(proxyTicketProvider, times(1)).getProxyTicket(service);
verify(clientHttpRequestExecution, never()).execute(request, null);
}
19
View Source File : CasAuthorizationInterceptorTest.java
License : MIT License
Project Creator : kakawait
License : MIT License
Project Creator : kakawait
@Test
public void intercept_ServiceWithExistingQueryParameters_ProxyTicketAsQueryParameter() throws IOException {
String service = "http://httpbin.org/get?a=test&x=test2";
ClientHttpRequestExecution clientHttpRequestExecution = mock(ClientHttpRequestExecution.clreplaced);
ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create(service));
String proxyTicket = "PT-21-c1gk6jBcfYnatLbNExfx-0623277bc36a";
when(proxyTicketProvider.getProxyTicket(service)).thenReturn(proxyTicket);
casAuthorizationInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(proxyTicketProvider, times(1)).getProxyTicket(service);
verify(clientHttpRequestExecution, times(1)).execute(httpRequestArgumentCaptor.capture(), isNull());
replacedertThat(httpRequestArgumentCaptor.getValue().getURI().toASCIIString()).isEqualTo(service + "&ticket=" + proxyTicket);
}
19
View Source File : CasAuthorizationInterceptorTest.java
License : MIT License
Project Creator : kakawait
License : MIT License
Project Creator : kakawait
@Test
public void intercept_ServiceWithExistingQueryParameters_ProxyTicketAsQueryEscapedParameter() throws IOException {
String service = "http://httpbin.org/get?a=test&x=test2&c=%22test3%22";
ClientHttpRequestExecution clientHttpRequestExecution = mock(ClientHttpRequestExecution.clreplaced);
ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create(service));
String proxyTicket = "PT-21-c1gk6jBcfYnatLbNExfx-0623277bc36a";
when(proxyTicketProvider.getProxyTicket(service)).thenReturn(proxyTicket);
casAuthorizationInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(proxyTicketProvider, times(1)).getProxyTicket(service);
verify(clientHttpRequestExecution, times(1)).execute(httpRequestArgumentCaptor.capture(), isNull());
replacedertThat(httpRequestArgumentCaptor.getValue().getURI().toASCIIString()).isEqualTo(service + "&ticket=" + proxyTicket);
}
19
View Source File : CasAuthorizationInterceptorTest.java
License : MIT License
Project Creator : kakawait
License : MIT License
Project Creator : kakawait
@Test
public void intercept_ServiceWithConflictQueryParameter_QueryParameterOverride() throws IOException {
String service = "http://httpbin.org/get?ticket=bob";
ClientHttpRequestExecution clientHttpRequestExecution = mock(ClientHttpRequestExecution.clreplaced);
ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create(service));
String proxyTicket = "PT-21-c1gk6jBcfYnatLbNExfx-0623277bc36a";
when(proxyTicketProvider.getProxyTicket(service)).thenReturn(proxyTicket);
casAuthorizationInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(proxyTicketProvider, times(1)).getProxyTicket(service);
verify(clientHttpRequestExecution, times(1)).execute(httpRequestArgumentCaptor.capture(), isNull());
replacedertThat(httpRequestArgumentCaptor.getValue().getURI().toASCIIString()).isEqualTo("http://httpbin.org/get?ticket=" + proxyTicket);
}
19
View Source File : CasAuthorizationInterceptorTest.java
License : MIT License
Project Creator : kakawait
License : MIT License
Project Creator : kakawait
@Test
public void intercept_BasicService_ProxyTicketAsQueryParameter() throws IOException {
String service = "http://httpbin.org/get";
ClientHttpRequestExecution clientHttpRequestExecution = mock(ClientHttpRequestExecution.clreplaced);
ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create(service));
String proxyTicket = "PT-21-c1gk6jBcfYnatLbNExfx-0623277bc36a";
when(proxyTicketProvider.getProxyTicket(service)).thenReturn(proxyTicket);
casAuthorizationInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(proxyTicketProvider, times(1)).getProxyTicket(service);
verify(clientHttpRequestExecution, times(1)).execute(httpRequestArgumentCaptor.capture(), isNull());
replacedertThat(httpRequestArgumentCaptor.getValue().getURI().toASCIIString()).isEqualTo(service + "?ticket=" + proxyTicket);
}
19
View Source File : DiscordHttpRequestFactory.java
License : GNU General Public License v3.0
Project Creator : JuniperBot
License : GNU General Public License v3.0
Project Creator : JuniperBot
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
ClientHttpRequest request = super.createRequest(uri, httpMethod);
HttpHeaders headers = request.getHeaders();
headers.add("User-Agent", "JuniperBot DiscordBot (https://github.com/goldrenard/JuniperBot, 1.0)");
headers.add("Connection", "keep-alive");
headers.add("Authorization", "Bot " + token);
return request;
}
19
View Source File : DiscordHttpRequestFactory.java
License : GNU General Public License v3.0
Project Creator : JuniperBot
License : GNU General Public License v3.0
Project Creator : JuniperBot
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
ClientHttpRequest request = super.createRequest(uri, httpMethod);
HttpHeaders headers = request.getHeaders();
headers.add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0");
headers.add("Connection", "keep-alive");
return request;
}
19
View Source File : WxApiHttpResponse.java
License : Apache License 2.0
Project Creator : FastBootWeixin
License : Apache License 2.0
Project Creator : FastBootWeixin
/**
* FastBootWeixin WxApiHttpResponse
* 包装AbstractClientHttpResponse,包装InputStream为pushbackInputStream,用于取前几个字符
*
* @author Guangshan
* @date 2017/08/23 22:31
* @since 0.1.2
*/
public final clreplaced WxApiHttpResponse extends AbstractClientHttpResponse {
private static final int WX_API_ERROR_CODE_END = 15;
private final ClientHttpResponse delegate;
private final ClientHttpRequest request;
private PushbackInputStream pushbackInputStream;
public WxApiHttpResponse(ClientHttpResponse delegate, ClientHttpRequest request) {
this.delegate = delegate;
this.request = request;
}
/**
* 你问我为什么要偷梁换柱?当然是因为微信接口返回的是JSON,但是Content-Type却是Text_Pain啦,是否要考虑判断内容?
* 暂时不需要,除非有些接口返回XML,也是这个头,那就坑爹了
*
* @return the result
*/
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = this.delegate.getHeaders();
if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
return headers;
}
if (headers.containsKey(HttpHeaders.CONTENT_TYPE) && headers.getContentType().equals(MediaType.TEXT_PLAIN)) {
headers.setContentType(MediaType.APPLICATION_JSON);
}
if (!headers.containsKey(WxWebUtils.X_WX_REQUEST_URL)) {
headers.add(WxWebUtils.X_WX_REQUEST_URL, request.getURI().toString());
}
return headers;
}
/**
* 装饰一下,返回可以重读的InputStream
*
* @return the result
* @throws IOException
*/
@Override
public InputStream getBody() throws IOException {
InputStream body = this.delegate.getBody();
if (body == null || body.markSupported() || body instanceof PushbackInputStream) {
return body;
} else if (this.pushbackInputStream == null) {
this.pushbackInputStream = new PushbackInputStream(body, WX_API_ERROR_CODE_END);
}
return this.pushbackInputStream;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return this.delegate.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return this.delegate.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return this.delegate.getStatusText();
}
@Override
public void close() {
this.delegate.close();
this.pushbackInputStream = null;
}
}
19
View Source File : WxApiHttpRequest.java
License : Apache License 2.0
Project Creator : FastBootWeixin
License : Apache License 2.0
Project Creator : FastBootWeixin
/**
* FastBootWeixin WxApiHttpRequest
* 包装ClientHttpRequest,用于生成包装过的ClientHttpResponse
*
* @author Guangshan
* @date 2017/08/23 22:31
* @since 0.1.2
*/
public final clreplaced WxApiHttpRequest implements ClientHttpRequest {
private ClientHttpRequest delegate;
public WxApiHttpRequest(ClientHttpRequest delegate) {
this.delegate = delegate;
}
@Override
public HttpMethod getMethod() {
return this.delegate.getMethod();
}
/**
* 同样是兼容SB2.0, Spring5才加入的这个方法
* 不写Override,写了在4.x版本会报错,注意递归调用
* @return
*/
public String getMethodValue() {
return this.delegate.getMethod().name();
}
@Override
public URI getURI() {
return this.delegate.getURI();
}
@Override
public ClientHttpResponse execute() throws IOException {
return new WxApiHttpResponse(this.delegate.execute(), this);
}
/**
* 针对下面这个比较恶心的魔法逻辑的说明:
* 由于Spring5在对ContentType是MULTIPART_FORM_DATA的头处理时自动添加了charset参数。
* see org.springframework.http.converter.FormHttpMessageConverter.writeMultipart
* 如果设置了multipartCharset,则不会添加charset参数。
* 但是在获取filename时又去判断如果设置了multipartCharset,则调用MimeDelegate.encode(filename, this.multipartCharset.name())
* 对filename进行encode,但是MimeDelegate调用了javax.mail.internet.MimeUtility这个类,这个类有可能没有被依赖进来,不是强依赖的
* 故会导致一样的报错。实在没办法切入源码了,故加入下面这个逻辑。
* 在Spring4中在multipartCharset为空时,也不会自动添加charset,故没有此问题。
* 而根本原因是微信的服务器兼容性太差了,header中的charset是有http标准规定的,竟然不兼容!
*
* @return OutputStream
* @throws IOException
*/
@Override
public OutputStream getBody() throws IOException {
HttpHeaders httpHeaders = this.delegate.getHeaders();
MediaType contentType = httpHeaders.getContentType();
if (contentType != null && contentType.includes(MediaType.MULTIPART_FORM_DATA)) {
Map<String, String> parameters = contentType.getParameters();
if (parameters.containsKey("charset")) {
Map<String, String> newParameters = new LinkedHashMap<>(contentType.getParameters());
newParameters.remove("charset");
MediaType newContentType = new MediaType(MediaType.MULTIPART_FORM_DATA, newParameters);
httpHeaders.setContentType(newContentType);
}
}
return this.delegate.getBody();
}
@Override
public HttpHeaders getHeaders() {
return this.delegate.getHeaders();
}
}
19
View Source File : CustomRequestCallBack.java
License : GNU General Public License v3.0
Project Creator : coti-io
License : GNU General Public License v3.0
Project Creator : coti-io
@Override
public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
clientHttpRequest.getHeaders().set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
clientHttpRequest.getBody().write(jacksonSerializer.serialize(request));
}
19
View Source File : CseRequestCallback.java
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
/**
* {@inheritDoc}
*/
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
orgCallback.doWithRequest(request);
CseClientHttpRequest req = (CseClientHttpRequest) request;
req.setResponseType(overrideResponseType());
if (!CseHttpEnreplacedy.clreplaced.isInstance(requestBody)) {
return;
}
CseHttpEnreplacedy<?> enreplacedy = (CseHttpEnreplacedy<?>) requestBody;
req.setContext(enreplacedy.getContext());
}
18
View Source File : RootUriRequestExpectationManagerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() throws Exception {
ClientHttpRequest request = mock(ClientHttpRequest.clreplaced);
given(request.getURI()).willReturn(new URI("http://spring.io/test"));
this.manager.validateRequest(request);
verify(this.delegate).validateRequest(request);
}
18
View Source File : RootUriRequestExpectationManagerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void validateRequestWhenRequestUrireplacedertionIsThrownShouldReplaceUriInMessage() throws Exception {
ClientHttpRequest request = mock(ClientHttpRequest.clreplaced);
given(request.getURI()).willReturn(new URI(this.uri + "/hello"));
given(this.delegate.validateRequest(any(ClientHttpRequest.clreplaced))).willThrow(new replacedertionError("Request URI expected:</hello> was:<http://example.com/bad>"));
replacedertThatExceptionOfType(replacedertionError.clreplaced).isThrownBy(() -> this.manager.validateRequest(request)).withMessageContaining("Request URI expected:<http://example.com/hello>");
}
18
View Source File : RestTemplateTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Brian Clozel
*/
@SuppressWarnings("unchecked")
public clreplaced RestTemplateTests {
private RestTemplate template;
private ClientHttpRequestFactory requestFactory;
private ClientHttpRequest request;
private ClientHttpResponse response;
private ResponseErrorHandler errorHandler;
@SuppressWarnings("rawtypes")
private HttpMessageConverter converter;
@Before
public void setup() {
requestFactory = mock(ClientHttpRequestFactory.clreplaced);
request = mock(ClientHttpRequest.clreplaced);
response = mock(ClientHttpResponse.clreplaced);
errorHandler = mock(ResponseErrorHandler.clreplaced);
converter = mock(HttpMessageConverter.clreplaced);
template = new RestTemplate(Collections.singletonList(converter));
template.setRequestFactory(requestFactory);
template.setErrorHandler(errorHandler);
}
@Test
public void varArgsTemplateVariables() throws Exception {
mockSentRequest(GET, "https://example.com/hotels/42/bookings/21");
mockResponseStatus(HttpStatus.OK);
template.execute("https://example.com/hotels/{hotel}/bookings/{booking}", GET, null, null, "42", "21");
verify(response).close();
}
@Test
public void varArgsNullTemplateVariable() throws Exception {
mockSentRequest(GET, "https://example.com/-foo");
mockResponseStatus(HttpStatus.OK);
template.execute("https://example.com/{first}-{last}", GET, null, null, null, "foo");
verify(response).close();
}
@Test
public void mapTemplateVariables() throws Exception {
mockSentRequest(GET, "https://example.com/hotels/42/bookings/42");
mockResponseStatus(HttpStatus.OK);
Map<String, String> vars = Collections.singletonMap("hotel", "42");
template.execute("https://example.com/hotels/{hotel}/bookings/{hotel}", GET, null, null, vars);
verify(response).close();
}
@Test
public void mapNullTemplateVariable() throws Exception {
mockSentRequest(GET, "https://example.com/-foo");
mockResponseStatus(HttpStatus.OK);
Map<String, String> vars = new HashMap<>(2);
vars.put("first", null);
vars.put("last", "foo");
template.execute("https://example.com/{first}-{last}", GET, null, null, vars);
verify(response).close();
}
// SPR-15201
@Test
public void uriTemplateWithTrailingSlash() throws Exception {
String url = "https://example.com/spring/";
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.OK);
template.execute(url, GET, null, null);
verify(response).close();
}
@Test
public void errorHandling() throws Exception {
String url = "https://example.com";
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR);
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).given(errorHandler).handleError(new URI(url), GET, response);
try {
template.execute(url, GET, null, null);
fail("HttpServerErrorException expected");
} catch (HttpServerErrorException ex) {
// expected
}
verify(response).close();
}
@Test
public void getForObject() throws Exception {
String expected = "Hello World";
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
mockTextResponseBody("Hello World");
String result = template.getForObject("https://example.com", String.clreplaced);
replacedertEquals("Invalid GET result", expected, result);
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void getUnsupportedMediaType() throws Exception {
mockSentRequest(GET, "https://example.com/resource");
mockResponseStatus(HttpStatus.OK);
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType supportedMediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType));
MediaType barBaz = new MediaType("bar", "baz");
mockResponseBody("Foo", new MediaType("bar", "baz"));
given(converter.canRead(String.clreplaced, barBaz)).willReturn(false);
try {
template.getForObject("https://example.com/{p}", String.clreplaced, "resource");
fail("UnsupportedMediaTypeException expected");
} catch (RestClientException ex) {
// expected
}
verify(response).close();
}
@Test
public void requestAvoidsDuplicateAcceptHeaderValues() throws Exception {
HttpMessageConverter firstConverter = mock(HttpMessageConverter.clreplaced);
given(firstConverter.canRead(any(), any())).willReturn(true);
given(firstConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpMessageConverter secondConverter = mock(HttpMessageConverter.clreplaced);
given(secondConverter.canRead(any(), any())).willReturn(true);
given(secondConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "https://example.com/", requestHeaders);
mockResponseStatus(HttpStatus.OK);
mockTextResponseBody("Hello World");
template.setMessageConverters(Arrays.asList(firstConverter, secondConverter));
template.getForObject("https://example.com/", String.clreplaced);
replacedertEquals("Sent duplicate Accept header values", 1, requestHeaders.getAccept().size());
}
@Test
public void getForEnreplacedy() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "https://example.com", requestHeaders);
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String expected = "Hello World";
mockTextResponseBody(expected);
ResponseEnreplacedy<String> result = template.getForEnreplacedy("https://example.com", String.clreplaced);
replacedertEquals("Invalid GET result", expected, result.getBody());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid Content-Type header", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
DefaultUriBuilderFactory uriTemplateHandler = new DefaultUriBuilderFactory();
template.setUriTemplateHandler(uriTemplateHandler);
mockSentRequest(GET, "https://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
mockResponseStatus(HttpStatus.OK);
given(response.getHeaders()).willReturn(new HttpHeaders());
given(response.getBody()).willReturn(StreamUtils.emptyInput());
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("hotel", "1");
uriVariables.put("publicpath", "pics/logo.png");
uriVariables.put("scale", "150x150");
String url = "https://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
template.getForObject(url, String.clreplaced, uriVariables);
verify(response).close();
}
@Test
public void headForHeaders() throws Exception {
mockSentRequest(HEAD, "https://example.com");
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders result = template.headForHeaders("https://example.com");
replacedertSame("Invalid headers returned", responseHeaders, result);
verify(response).close();
}
@Test
public void postForLocation() throws Exception {
mockSentRequest(POST, "https://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
URI result = template.postForLocation("https://example.com", helloWorld);
replacedertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyContentType() throws Exception {
mockSentRequest(POST, "https://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(MediaType.TEXT_PLAIN);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(helloWorld, enreplacedyHeaders);
URI result = template.postForLocation("https://example.com", enreplacedy);
replacedertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyCustomHeader() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
URI result = template.postForLocation("https://example.com", enreplacedy);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader"));
verify(response).close();
}
@Test
public void postForLocationNoLocation() throws Exception {
mockSentRequest(POST, "https://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
URI result = template.postForLocation("https://example.com", "Hello World");
replacedertNull("Invalid POST result", result);
verify(response).close();
}
@Test
public void postForLocationNull() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
template.postForLocation("https://example.com", null);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForObject() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
String result = template.postForObject("https://example.com", "Hello World", String.clreplaced);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void postForEnreplacedy() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
ResponseEnreplacedy<String> result = template.postForEnreplacedy("https://example.com", "Hello World", String.clreplaced);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void postForObjectNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
given(converter.read(String.clreplaced, response)).willReturn(null);
String result = template.postForObject("https://example.com", null, String.clreplaced);
replacedertNull("Invalid POST result", result);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForEnreplacedyNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
given(converter.read(String.clreplaced, response)).willReturn(null);
ResponseEnreplacedy<String> result = template.postForEnreplacedy("https://example.com", null, String.clreplaced);
replacedertFalse("Invalid POST result", result.hasBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void put() throws Exception {
mockTextPlainHttpMessageConverter();
mockSentRequest(PUT, "https://example.com");
mockResponseStatus(HttpStatus.OK);
template.put("https://example.com", "Hello World");
verify(response).close();
}
@Test
public void putNull() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PUT, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
template.put("https://example.com", null);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void patchForObject() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PATCH, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody("42", MediaType.TEXT_PLAIN);
String result = template.patchForObject("https://example.com", "Hello World", String.clreplaced);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void patchForObjectNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PATCH, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
String result = template.patchForObject("https://example.com", null, String.clreplaced);
replacedertNull("Invalid POST result", result);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void delete() throws Exception {
mockSentRequest(DELETE, "https://example.com");
mockResponseStatus(HttpStatus.OK);
template.delete("https://example.com");
verify(response).close();
}
@Test
public void optionsForAllow() throws Exception {
mockSentRequest(OPTIONS, "https://example.com");
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(GET, POST);
responseHeaders.setAllow(expected);
given(response.getHeaders()).willReturn(responseHeaders);
Set<HttpMethod> result = template.optionsForAllow("https://example.com");
replacedertEquals("Invalid OPTIONS result", expected, result);
verify(response).close();
}
// SPR-9325, SPR-13860
@Test
public void ioException() throws Exception {
String url = "https://example.com/resource?access_token=123";
mockSentRequest(GET, url);
mockHttpMessageConverter(new MediaType("foo", "bar"), String.clreplaced);
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(url, String.clreplaced);
fail("RestClientException expected");
} catch (ResourceAccessException ex) {
replacedertEquals("I/O error on GET request for \"https://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure", ex.getMessage());
}
}
// SPR-15900
@Test
public void ioExceptionWithEmptyQueryString() throws Exception {
// https://example.com/resource?
URI uri = new URI("https", "example.com", "/resource", "", null);
given(converter.canRead(String.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(parseMediaType("foo/bar")));
given(requestFactory.createRequest(uri, GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(uri, String.clreplaced);
fail("RestClientException expected");
} catch (ResourceAccessException ex) {
replacedertEquals("I/O error on GET request for \"https://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure", ex.getMessage());
}
}
@Test
public void exchange() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
ResponseEnreplacedy<String> result = template.exchange("https://example.com", POST, enreplacedy, String.clreplaced);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.clreplaced);
template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {
};
given(converter.canRead(intList.getType(), null, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(converter.canWrite(String.clreplaced, String.clreplaced, null)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
List<Integer> expected = Collections.singletonList(42);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
mockResponseStatus(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.clreplaced))).willReturn(expected);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
ResponseEnreplacedy<List<Integer>> result = template.exchange("https://example.com", POST, requestEnreplacedy, intList);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
// SPR-15066
@Test
public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(Collections.singletonList(interceptor));
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.add("MyHeader", "MyEnreplacedyValue");
HttpEnreplacedy<Void> enreplacedy = new HttpEnreplacedy<>(null, enreplacedyHeaders);
template.exchange("https://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader"), contains("MyEnreplacedyValue", "MyInterceptorValue"));
verify(response).close();
}
// SPR-15066
@Test
public void requestInterceptorCanAddExistingHeaderValueWithBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(Collections.singletonList(interceptor));
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.clreplaced, contentType)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(contentType);
enreplacedyHeaders.add("MyHeader", "MyEnreplacedyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
template.exchange("https://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader"), contains("MyEnreplacedyValue", "MyInterceptorValue"));
verify(response).close();
}
private void mockSentRequest(HttpMethod method, String uri) throws Exception {
mockSentRequest(method, uri, new HttpHeaders());
}
private void mockSentRequest(HttpMethod method, String uri, HttpHeaders requestHeaders) throws Exception {
given(requestFactory.createRequest(new URI(uri), method)).willReturn(request);
given(request.getHeaders()).willReturn(requestHeaders);
}
private void mockResponseStatus(HttpStatus responseStatus) throws Exception {
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(responseStatus.isError());
given(response.getStatusCode()).willReturn(responseStatus);
given(response.getRawStatusCode()).willReturn(responseStatus.value());
given(response.getStatusText()).willReturn(responseStatus.getReasonPhrase());
}
private void mockTextPlainHttpMessageConverter() {
mockHttpMessageConverter(MediaType.TEXT_PLAIN, String.clreplaced);
}
private void mockHttpMessageConverter(MediaType mediaType, Clreplaced type) {
given(converter.canRead(type, null)).willReturn(true);
given(converter.canRead(type, mediaType)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
given(converter.canRead(type, mediaType)).willReturn(true);
given(converter.canWrite(type, null)).willReturn(true);
given(converter.canWrite(type, mediaType)).willReturn(true);
}
private void mockTextResponseBody(String expectedBody) throws Exception {
mockResponseBody(expectedBody, MediaType.TEXT_PLAIN);
}
private void mockResponseBody(String expectedBody, MediaType mediaType) throws Exception {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(mediaType);
responseHeaders.setContentLength(expectedBody.length());
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expectedBody.getBytes()));
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expectedBody);
}
}
18
View Source File : AbstractRequestExpectationManager.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Return details of executed requests.
*/
protected String getRequestDetails() {
StringBuilder sb = new StringBuilder();
sb.append(this.requests.size()).append(" request(s) executed");
if (!this.requests.isEmpty()) {
sb.append(":\n");
for (ClientHttpRequest request : this.requests) {
sb.append(request.toString()).append("\n");
}
} else {
sb.append(".\n");
}
return sb.toString();
}
18
View Source File : AbstractRequestExpectationManager.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@SuppressWarnings("deprecation")
@Override
public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
RequestExpectation expectation = null;
synchronized (this.requests) {
if (this.requests.isEmpty()) {
afterExpectationsDeclared();
}
try {
// Try this first for backwards compatibility
ClientHttpResponse response = validateRequestInternal(request);
if (response != null) {
return response;
} else {
expectation = matchRequest(request);
}
} catch (Throwable ex) {
this.requestFailures.put(request, ex);
throw ex;
} finally {
this.requests.add(request);
}
}
return expectation.createResponse(request);
}
18
View Source File : RestTemplateTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Unit tests for {@link RestTemplate}.
*
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Brian Clozel
* @author Sam Brannen
*/
@SuppressWarnings("unchecked")
public clreplaced RestTemplateTests {
private RestTemplate template;
private ClientHttpRequestFactory requestFactory;
private ClientHttpRequest request;
private ClientHttpResponse response;
private ResponseErrorHandler errorHandler;
@SuppressWarnings("rawtypes")
private HttpMessageConverter converter;
@BeforeEach
public void setup() {
requestFactory = mock(ClientHttpRequestFactory.clreplaced);
request = mock(ClientHttpRequest.clreplaced);
response = mock(ClientHttpResponse.clreplaced);
errorHandler = mock(ResponseErrorHandler.clreplaced);
converter = mock(HttpMessageConverter.clreplaced);
template = new RestTemplate(Collections.singletonList(converter));
template.setRequestFactory(requestFactory);
template.setErrorHandler(errorHandler);
}
@Test
public void constructorPreconditions() {
replacedertThatIllegalArgumentException().isThrownBy(() -> new RestTemplate((List<HttpMessageConverter<?>>) null)).withMessage("At least one HttpMessageConverter is required");
replacedertThatIllegalArgumentException().isThrownBy(() -> new RestTemplate(Arrays.asList(null, this.converter))).withMessage("The HttpMessageConverter list must not contain null elements");
}
@Test
public void setMessageConvertersPreconditions() {
replacedertThatIllegalArgumentException().isThrownBy(() -> template.setMessageConverters((List<HttpMessageConverter<?>>) null)).withMessage("At least one HttpMessageConverter is required");
replacedertThatIllegalArgumentException().isThrownBy(() -> template.setMessageConverters(Arrays.asList(null, this.converter))).withMessage("The HttpMessageConverter list must not contain null elements");
}
@Test
public void varArgsTemplateVariables() throws Exception {
mockSentRequest(GET, "https://example.com/hotels/42/bookings/21");
mockResponseStatus(HttpStatus.OK);
template.execute("https://example.com/hotels/{hotel}/bookings/{booking}", GET, null, null, "42", "21");
verify(response).close();
}
@Test
public void varArgsNullTemplateVariable() throws Exception {
mockSentRequest(GET, "https://example.com/-foo");
mockResponseStatus(HttpStatus.OK);
template.execute("https://example.com/{first}-{last}", GET, null, null, null, "foo");
verify(response).close();
}
@Test
public void mapTemplateVariables() throws Exception {
mockSentRequest(GET, "https://example.com/hotels/42/bookings/42");
mockResponseStatus(HttpStatus.OK);
Map<String, String> vars = Collections.singletonMap("hotel", "42");
template.execute("https://example.com/hotels/{hotel}/bookings/{hotel}", GET, null, null, vars);
verify(response).close();
}
@Test
public void mapNullTemplateVariable() throws Exception {
mockSentRequest(GET, "https://example.com/-foo");
mockResponseStatus(HttpStatus.OK);
Map<String, String> vars = new HashMap<>(2);
vars.put("first", null);
vars.put("last", "foo");
template.execute("https://example.com/{first}-{last}", GET, null, null, vars);
verify(response).close();
}
// SPR-15201
@Test
public void uriTemplateWithTrailingSlash() throws Exception {
String url = "https://example.com/spring/";
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.OK);
template.execute(url, GET, null, null);
verify(response).close();
}
@Test
public void errorHandling() throws Exception {
String url = "https://example.com";
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR);
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).given(errorHandler).handleError(new URI(url), GET, response);
replacedertThatExceptionOfType(HttpServerErrorException.clreplaced).isThrownBy(() -> template.execute(url, GET, null, null));
verify(response).close();
}
@Test
public void getForObject() throws Exception {
String expected = "Hello World";
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
mockTextResponseBody("Hello World");
String result = template.getForObject("https://example.com", String.clreplaced);
replacedertThat(result).as("Invalid GET result").isEqualTo(expected);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
verify(response).close();
}
@Test
public void getUnsupportedMediaType() throws Exception {
mockSentRequest(GET, "https://example.com/resource");
mockResponseStatus(HttpStatus.OK);
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType supportedMediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType));
MediaType barBaz = new MediaType("bar", "baz");
mockResponseBody("Foo", new MediaType("bar", "baz"));
given(converter.canRead(String.clreplaced, barBaz)).willReturn(false);
replacedertThatExceptionOfType(RestClientException.clreplaced).isThrownBy(() -> template.getForObject("https://example.com/{p}", String.clreplaced, "resource"));
verify(response).close();
}
@Test
public void requestAvoidsDuplicateAcceptHeaderValues() throws Exception {
HttpMessageConverter<?> firstConverter = mock(HttpMessageConverter.clreplaced);
given(firstConverter.canRead(any(), any())).willReturn(true);
given(firstConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpMessageConverter<?> secondConverter = mock(HttpMessageConverter.clreplaced);
given(secondConverter.canRead(any(), any())).willReturn(true);
given(secondConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "https://example.com/", requestHeaders);
mockResponseStatus(HttpStatus.OK);
mockTextResponseBody("Hello World");
template.setMessageConverters(Arrays.asList(firstConverter, secondConverter));
template.getForObject("https://example.com/", String.clreplaced);
replacedertThat(requestHeaders.getAccept().size()).as("Sent duplicate Accept header values").isEqualTo(1);
}
@Test
public void getForEnreplacedy() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "https://example.com", requestHeaders);
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String expected = "Hello World";
mockTextResponseBody(expected);
ResponseEnreplacedy<String> result = template.getForEnreplacedy("https://example.com", String.clreplaced);
replacedertThat(result.getBody()).as("Invalid GET result").isEqualTo(expected);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
replacedertThat(result.getHeaders().getContentType()).as("Invalid Content-Type header").isEqualTo(MediaType.TEXT_PLAIN);
replacedertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
verify(response).close();
}
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
DefaultUriBuilderFactory uriTemplateHandler = new DefaultUriBuilderFactory();
template.setUriTemplateHandler(uriTemplateHandler);
mockSentRequest(GET, "https://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
mockResponseStatus(HttpStatus.OK);
given(response.getHeaders()).willReturn(new HttpHeaders());
given(response.getBody()).willReturn(StreamUtils.emptyInput());
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("hotel", "1");
uriVariables.put("publicpath", "pics/logo.png");
uriVariables.put("scale", "150x150");
String url = "https://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
template.getForObject(url, String.clreplaced, uriVariables);
verify(response).close();
}
@Test
public void headForHeaders() throws Exception {
mockSentRequest(HEAD, "https://example.com");
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders result = template.headForHeaders("https://example.com");
replacedertThat(result).as("Invalid headers returned").isSameAs(responseHeaders);
verify(response).close();
}
@Test
public void postForLocation() throws Exception {
mockSentRequest(POST, "https://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
URI result = template.postForLocation("https://example.com", helloWorld);
replacedertThat(result).as("Invalid POST result").isEqualTo(expected);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyContentType() throws Exception {
mockSentRequest(POST, "https://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(MediaType.TEXT_PLAIN);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(helloWorld, enreplacedyHeaders);
URI result = template.postForLocation("https://example.com", enreplacedy);
replacedertThat(result).as("Invalid POST result").isEqualTo(expected);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyCustomHeader() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
URI result = template.postForLocation("https://example.com", enreplacedy);
replacedertThat(result).as("Invalid POST result").isEqualTo(expected);
replacedertThat(requestHeaders.getFirst("MyHeader")).as("No custom header set").isEqualTo("MyValue");
verify(response).close();
}
@Test
public void postForLocationNoLocation() throws Exception {
mockSentRequest(POST, "https://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
URI result = template.postForLocation("https://example.com", "Hello World");
replacedertThat(result).as("Invalid POST result").isNull();
verify(response).close();
}
@Test
public void postForLocationNull() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
template.postForLocation("https://example.com", null);
replacedertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0);
verify(response).close();
}
@Test
public void postForObject() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
String result = template.postForObject("https://example.com", "Hello World", String.clreplaced);
replacedertThat(result).as("Invalid POST result").isEqualTo(expected);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
verify(response).close();
}
@Test
public void postForEnreplacedy() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
ResponseEnreplacedy<String> result = template.postForEnreplacedy("https://example.com", "Hello World", String.clreplaced);
replacedertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected);
replacedertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
replacedertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
verify(response).close();
}
@Test
public void postForObjectNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
given(converter.read(String.clreplaced, response)).willReturn(null);
String result = template.postForObject("https://example.com", null, String.clreplaced);
replacedertThat(result).as("Invalid POST result").isNull();
replacedertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0);
verify(response).close();
}
@Test
public void postForEnreplacedyNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
given(converter.read(String.clreplaced, response)).willReturn(null);
ResponseEnreplacedy<String> result = template.postForEnreplacedy("https://example.com", null, String.clreplaced);
replacedertThat(result.hasBody()).as("Invalid POST result").isFalse();
replacedertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN);
replacedertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0);
replacedertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
verify(response).close();
}
@Test
public void put() throws Exception {
mockTextPlainHttpMessageConverter();
mockSentRequest(PUT, "https://example.com");
mockResponseStatus(HttpStatus.OK);
template.put("https://example.com", "Hello World");
verify(response).close();
}
@Test
public void putNull() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PUT, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
template.put("https://example.com", null);
replacedertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0);
verify(response).close();
}
// gh-23740
@Test
public void headerAcceptAllOnPut() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(500).setBody("internal server error"));
server.start();
try {
template.setRequestFactory(new SimpleClientHttpRequestFactory());
template.put(server.url("/internal/server/error").uri(), null);
replacedertThat(server.takeRequest().getHeader("Accept")).isEqualTo("*/*");
} finally {
server.shutdown();
}
}
// gh-23740
@Test
public void keepGivenAcceptHeaderOnPut() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(500).setBody("internal server error"));
server.start();
try {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(null, headers);
template.setRequestFactory(new SimpleClientHttpRequestFactory());
template.exchange(server.url("/internal/server/error").uri(), PUT, enreplacedy, Void.clreplaced);
RecordedRequest request = server.takeRequest();
final List<List<String>> accepts = request.getHeaders().toMultimap().entrySet().stream().filter(entry -> entry.getKey().equalsIgnoreCase("accept")).map(Entry::getValue).collect(Collectors.toList());
replacedertThat(accepts).hreplacedize(1);
replacedertThat(accepts.get(0)).hreplacedize(1);
replacedertThat(accepts.get(0).get(0)).isEqualTo("application/json");
} finally {
server.shutdown();
}
}
@Test
public void patchForObject() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PATCH, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody("42", MediaType.TEXT_PLAIN);
String result = template.patchForObject("https://example.com", "Hello World", String.clreplaced);
replacedertThat(result).as("Invalid POST result").isEqualTo(expected);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
verify(response).close();
}
@Test
public void patchForObjectNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PATCH, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
String result = template.patchForObject("https://example.com", null, String.clreplaced);
replacedertThat(result).as("Invalid POST result").isNull();
replacedertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0);
verify(response).close();
}
@Test
public void delete() throws Exception {
mockSentRequest(DELETE, "https://example.com");
mockResponseStatus(HttpStatus.OK);
template.delete("https://example.com");
verify(response).close();
}
// gh-23740
@Test
public void headerAcceptAllOnDelete() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(500).setBody("internal server error"));
server.start();
try {
template.setRequestFactory(new SimpleClientHttpRequestFactory());
template.delete(server.url("/internal/server/error").uri());
replacedertThat(server.takeRequest().getHeader("Accept")).isEqualTo("*/*");
} finally {
server.shutdown();
}
}
@Test
public void optionsForAllow() throws Exception {
mockSentRequest(OPTIONS, "https://example.com");
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(GET, POST);
responseHeaders.setAllow(expected);
given(response.getHeaders()).willReturn(responseHeaders);
Set<HttpMethod> result = template.optionsForAllow("https://example.com");
replacedertThat(result).as("Invalid OPTIONS result").isEqualTo(expected);
verify(response).close();
}
// SPR-9325, SPR-13860
@Test
public void ioException() throws Exception {
String url = "https://example.com/resource?access_token=123";
mockSentRequest(GET, url);
mockHttpMessageConverter(new MediaType("foo", "bar"), String.clreplaced);
given(request.execute()).willThrow(new IOException("Socket failure"));
replacedertThatExceptionOfType(ResourceAccessException.clreplaced).isThrownBy(() -> template.getForObject(url, String.clreplaced)).withMessage("I/O error on GET request for \"https://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure");
}
// SPR-15900
@Test
public void ioExceptionWithEmptyQueryString() throws Exception {
// https://example.com/resource?
URI uri = new URI("https", "example.com", "/resource", "", null);
given(converter.canRead(String.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(parseMediaType("foo/bar")));
given(requestFactory.createRequest(uri, GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willThrow(new IOException("Socket failure"));
replacedertThatExceptionOfType(ResourceAccessException.clreplaced).isThrownBy(() -> template.getForObject(uri, String.clreplaced)).withMessage("I/O error on GET request for \"https://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure");
}
@Test
public void exchange() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
ResponseEnreplacedy<String> result = template.exchange("https://example.com", POST, enreplacedy, String.clreplaced);
replacedertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected);
replacedertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
replacedertThat(requestHeaders.getFirst("MyHeader")).as("Invalid custom header").isEqualTo("MyValue");
replacedertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
verify(response).close();
}
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.clreplaced);
template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {
};
given(converter.canRead(intList.getType(), null, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(converter.canWrite(String.clreplaced, String.clreplaced, null)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
List<Integer> expected = Collections.singletonList(42);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
mockResponseStatus(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.clreplaced))).willReturn(expected);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
ResponseEnreplacedy<List<Integer>> result = template.exchange("https://example.com", POST, requestEnreplacedy, intList);
replacedertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected);
replacedertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN);
replacedertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE);
replacedertThat(requestHeaders.getFirst("MyHeader")).as("Invalid custom header").isEqualTo("MyValue");
replacedertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
verify(response).close();
}
// SPR-15066
@Test
public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(Collections.singletonList(interceptor));
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.add("MyHeader", "MyEnreplacedyValue");
HttpEnreplacedy<Void> enreplacedy = new HttpEnreplacedy<>(null, enreplacedyHeaders);
template.exchange("https://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader")).contains("MyEnreplacedyValue", "MyInterceptorValue");
verify(response).close();
}
// SPR-15066
@Test
public void requestInterceptorCanAddExistingHeaderValueWithBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(Collections.singletonList(interceptor));
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.clreplaced, contentType)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(contentType);
enreplacedyHeaders.add("MyHeader", "MyEnreplacedyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
template.exchange("https://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader")).contains("MyEnreplacedyValue", "MyInterceptorValue");
verify(response).close();
}
@Test
public void clientHttpRequestInitializerAndRequestInterceptorAreBothApplied() throws Exception {
ClientHttpRequestInitializer initializer = request -> request.getHeaders().add("MyHeader", "MyInitializerValue");
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setClientHttpRequestInitializers(Collections.singletonList(initializer));
template.setInterceptors(Collections.singletonList(interceptor));
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.clreplaced, contentType)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "https://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(contentType);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
template.exchange("https://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader")).contains("MyInterceptorValue", "MyInitializerValue");
verify(response).close();
}
private void mockSentRequest(HttpMethod method, String uri) throws Exception {
mockSentRequest(method, uri, new HttpHeaders());
}
private void mockSentRequest(HttpMethod method, String uri, HttpHeaders requestHeaders) throws Exception {
given(requestFactory.createRequest(new URI(uri), method)).willReturn(request);
given(request.getHeaders()).willReturn(requestHeaders);
}
private void mockResponseStatus(HttpStatus responseStatus) throws Exception {
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(responseStatus.isError());
given(response.getStatusCode()).willReturn(responseStatus);
given(response.getRawStatusCode()).willReturn(responseStatus.value());
given(response.getStatusText()).willReturn(responseStatus.getReasonPhrase());
}
private void mockTextPlainHttpMessageConverter() {
mockHttpMessageConverter(MediaType.TEXT_PLAIN, String.clreplaced);
}
private void mockHttpMessageConverter(MediaType mediaType, Clreplaced<?> type) {
given(converter.canRead(type, null)).willReturn(true);
given(converter.canRead(type, mediaType)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
given(converter.canRead(type, mediaType)).willReturn(true);
given(converter.canWrite(type, null)).willReturn(true);
given(converter.canWrite(type, mediaType)).willReturn(true);
}
private void mockTextResponseBody(String expectedBody) throws Exception {
mockResponseBody(expectedBody, MediaType.TEXT_PLAIN);
}
private void mockResponseBody(String expectedBody, MediaType mediaType) throws Exception {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(mediaType);
responseHeaders.setContentLength(expectedBody.length());
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expectedBody.getBytes()));
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expectedBody);
}
}
18
View Source File : BasicAuthorizationInterceptorTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void interceptShouldAddHeader() throws Exception {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.clreplaced);
byte[] body = new byte[] {};
new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body, execution);
verify(execution).execute(request, body);
replacedertThat(request.getHeaders().getFirst("Authorization")).isEqualTo("Basic c3ByaW5nOmJvb3Q=");
}
18
View Source File : ClientRequestTest.java
License : Apache License 2.0
Project Creator : openapi4j
License : Apache License 2.0
Project Creator : openapi4j
@Test
public void bodyIsNotSetForNonMockSource() throws IOException {
ClientHttpRequest source = Mockito.mock(ClientHttpRequest.clreplaced);
Mockito.when(source.getMethodValue()).thenReturn(HttpMethod.POST.name());
Mockito.when(source.getURI()).thenReturn(URI.create("http://localhost/"));
Mockito.when(source.getHeaders()).thenReturn(new HttpHeaders());
Request actual = ClientRequest.of(source);
replacedertEquals(Request.Method.POST, actual.getMethod());
replacedertNull(actual.getBody());
}
18
View Source File : RestTemplateTests.java
License : MIT License
Project Creator : mindcarver
License : MIT License
Project Creator : mindcarver
/**
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Brian Clozel
*/
@SuppressWarnings("unchecked")
public clreplaced RestTemplateTests {
private RestTemplate template;
private ClientHttpRequestFactory requestFactory;
private ClientHttpRequest request;
private ClientHttpResponse response;
private ResponseErrorHandler errorHandler;
@SuppressWarnings("rawtypes")
private HttpMessageConverter converter;
@Before
public void setup() {
requestFactory = mock(ClientHttpRequestFactory.clreplaced);
request = mock(ClientHttpRequest.clreplaced);
response = mock(ClientHttpResponse.clreplaced);
errorHandler = mock(ResponseErrorHandler.clreplaced);
converter = mock(HttpMessageConverter.clreplaced);
template = new RestTemplate(Collections.singletonList(converter));
template.setRequestFactory(requestFactory);
template.setErrorHandler(errorHandler);
}
@Test
public void varArgsTemplateVariables() throws Exception {
mockSentRequest(GET, "http://example.com/hotels/42/bookings/21");
mockResponseStatus(HttpStatus.OK);
template.execute("http://example.com/hotels/{hotel}/bookings/{booking}", GET, null, null, "42", "21");
verify(response).close();
}
@Test
public void varArgsNullTemplateVariable() throws Exception {
mockSentRequest(GET, "http://example.com/-foo");
mockResponseStatus(HttpStatus.OK);
template.execute("http://example.com/{first}-{last}", GET, null, null, null, "foo");
verify(response).close();
}
@Test
public void mapTemplateVariables() throws Exception {
mockSentRequest(GET, "http://example.com/hotels/42/bookings/42");
mockResponseStatus(HttpStatus.OK);
Map<String, String> vars = Collections.singletonMap("hotel", "42");
template.execute("http://example.com/hotels/{hotel}/bookings/{hotel}", GET, null, null, vars);
verify(response).close();
}
@Test
public void mapNullTemplateVariable() throws Exception {
mockSentRequest(GET, "http://example.com/-foo");
mockResponseStatus(HttpStatus.OK);
Map<String, String> vars = new HashMap<>(2);
vars.put("first", null);
vars.put("last", "foo");
template.execute("http://example.com/{first}-{last}", GET, null, null, vars);
verify(response).close();
}
// SPR-15201
@Test
public void uriTemplateWithTrailingSlash() throws Exception {
String url = "http://example.com/spring/";
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.OK);
template.execute(url, GET, null, null);
verify(response).close();
}
@Test
public void errorHandling() throws Exception {
String url = "http://example.com";
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR);
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).given(errorHandler).handleError(new URI(url), GET, response);
try {
template.execute(url, GET, null, null);
fail("HttpServerErrorException expected");
} catch (HttpServerErrorException ex) {
// expected
}
verify(response).close();
}
@Test
public void getForObject() throws Exception {
String expected = "Hello World";
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
mockTextResponseBody("Hello World");
String result = template.getForObject("http://example.com", String.clreplaced);
replacedertEquals("Invalid GET result", expected, result);
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void getUnsupportedMediaType() throws Exception {
mockSentRequest(GET, "http://example.com/resource");
mockResponseStatus(HttpStatus.OK);
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType supportedMediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType));
MediaType barBaz = new MediaType("bar", "baz");
mockResponseBody("Foo", new MediaType("bar", "baz"));
given(converter.canRead(String.clreplaced, barBaz)).willReturn(false);
try {
template.getForObject("http://example.com/{p}", String.clreplaced, "resource");
fail("UnsupportedMediaTypeException expected");
} catch (RestClientException ex) {
// expected
}
verify(response).close();
}
@Test
public void requestAvoidsDuplicateAcceptHeaderValues() throws Exception {
HttpMessageConverter firstConverter = mock(HttpMessageConverter.clreplaced);
given(firstConverter.canRead(any(), any())).willReturn(true);
given(firstConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpMessageConverter secondConverter = mock(HttpMessageConverter.clreplaced);
given(secondConverter.canRead(any(), any())).willReturn(true);
given(secondConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "http://example.com/", requestHeaders);
mockResponseStatus(HttpStatus.OK);
mockTextResponseBody("Hello World");
template.setMessageConverters(Arrays.asList(firstConverter, secondConverter));
template.getForObject("http://example.com/", String.clreplaced);
replacedertEquals("Sent duplicate Accept header values", 1, requestHeaders.getAccept().size());
}
@Test
public void getForEnreplacedy() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(GET, "http://example.com", requestHeaders);
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String expected = "Hello World";
mockTextResponseBody(expected);
ResponseEnreplacedy<String> result = template.getForEnreplacedy("http://example.com", String.clreplaced);
replacedertEquals("Invalid GET result", expected, result.getBody());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid Content-Type header", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
DefaultUriBuilderFactory uriTemplateHandler = new DefaultUriBuilderFactory();
template.setUriTemplateHandler(uriTemplateHandler);
mockSentRequest(GET, "http://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
mockResponseStatus(HttpStatus.OK);
given(response.getHeaders()).willReturn(new HttpHeaders());
given(response.getBody()).willReturn(StreamUtils.emptyInput());
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("hotel", "1");
uriVariables.put("publicpath", "pics/logo.png");
uriVariables.put("scale", "150x150");
String url = "http://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
template.getForObject(url, String.clreplaced, uriVariables);
verify(response).close();
}
@Test
public void headForHeaders() throws Exception {
mockSentRequest(HEAD, "http://example.com");
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders result = template.headForHeaders("http://example.com");
replacedertSame("Invalid headers returned", responseHeaders, result);
verify(response).close();
}
@Test
public void postForLocation() throws Exception {
mockSentRequest(POST, "http://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
URI result = template.postForLocation("http://example.com", helloWorld);
replacedertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyContentType() throws Exception {
mockSentRequest(POST, "http://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(MediaType.TEXT_PLAIN);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>(helloWorld, enreplacedyHeaders);
URI result = template.postForLocation("http://example.com", enreplacedy);
replacedertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyCustomHeader() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
URI result = template.postForLocation("http://example.com", enreplacedy);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader"));
verify(response).close();
}
@Test
public void postForLocationNoLocation() throws Exception {
mockSentRequest(POST, "http://example.com");
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
URI result = template.postForLocation("http://example.com", "Hello World");
replacedertNull("Invalid POST result", result);
verify(response).close();
}
@Test
public void postForLocationNull() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
template.postForLocation("http://example.com", null);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForObject() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
String result = template.postForObject("http://example.com", "Hello World", String.clreplaced);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void postForEnreplacedy() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
ResponseEnreplacedy<String> result = template.postForEnreplacedy("http://example.com", "Hello World", String.clreplaced);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void postForObjectNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
given(converter.read(String.clreplaced, response)).willReturn(null);
String result = template.postForObject("http://example.com", null, String.clreplaced);
replacedertNull("Invalid POST result", result);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForEnreplacedyNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
given(converter.read(String.clreplaced, response)).willReturn(null);
ResponseEnreplacedy<String> result = template.postForEnreplacedy("http://example.com", null, String.clreplaced);
replacedertFalse("Invalid POST result", result.hasBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void put() throws Exception {
mockTextPlainHttpMessageConverter();
mockSentRequest(PUT, "http://example.com");
mockResponseStatus(HttpStatus.OK);
template.put("http://example.com", "Hello World");
verify(response).close();
}
@Test
public void putNull() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PUT, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
template.put("http://example.com", null);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void patchForObject() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PATCH, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody("42", MediaType.TEXT_PLAIN);
String result = template.patchForObject("http://example.com", "Hello World", String.clreplaced);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void patchForObjectNull() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(PATCH, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(StreamUtils.emptyInput());
String result = template.patchForObject("http://example.com", null, String.clreplaced);
replacedertNull("Invalid POST result", result);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void delete() throws Exception {
mockSentRequest(DELETE, "http://example.com");
mockResponseStatus(HttpStatus.OK);
template.delete("http://example.com");
verify(response).close();
}
@Test
public void optionsForAllow() throws Exception {
mockSentRequest(OPTIONS, "http://example.com");
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(GET, POST);
responseHeaders.setAllow(expected);
given(response.getHeaders()).willReturn(responseHeaders);
Set<HttpMethod> result = template.optionsForAllow("http://example.com");
replacedertEquals("Invalid OPTIONS result", expected, result);
verify(response).close();
}
// SPR-9325, SPR-13860
@Test
public void ioException() throws Exception {
String url = "http://example.com/resource?access_token=123";
mockSentRequest(GET, url);
mockHttpMessageConverter(new MediaType("foo", "bar"), String.clreplaced);
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(url, String.clreplaced);
fail("RestClientException expected");
} catch (ResourceAccessException ex) {
replacedertEquals("I/O error on GET request for \"http://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure", ex.getMessage());
}
}
// SPR-15900
@Test
public void ioExceptionWithEmptyQueryString() throws Exception {
// http://example.com/resource?
URI uri = new URI("http", "example.com", "/resource", "", null);
given(converter.canRead(String.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(parseMediaType("foo/bar")));
given(requestFactory.createRequest(uri, GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(uri, String.clreplaced);
fail("RestClientException expected");
} catch (ResourceAccessException ex) {
replacedertEquals("I/O error on GET request for \"http://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure", ex.getMessage());
}
}
@Test
public void exchange() throws Exception {
mockTextPlainHttpMessageConverter();
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
String expected = "42";
mockResponseBody(expected, MediaType.TEXT_PLAIN);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
ResponseEnreplacedy<String> result = template.exchange("http://example.com", POST, enreplacedy, String.clreplaced);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.clreplaced);
template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {
};
given(converter.canRead(intList.getType(), null, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(converter.canWrite(String.clreplaced, String.clreplaced, null)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
List<Integer> expected = Collections.singletonList(42);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
mockResponseStatus(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.clreplaced))).willReturn(expected);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
ResponseEnreplacedy<List<Integer>> result = template.exchange("http://example.com", POST, requestEnreplacedy, intList);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
// SPR-15066
@Test
public void requestInterceptorCanAddExistingHeaderValueWithoutBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(Collections.singletonList(interceptor));
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.add("MyHeader", "MyEnreplacedyValue");
HttpEnreplacedy<Void> enreplacedy = new HttpEnreplacedy<>(null, enreplacedyHeaders);
template.exchange("http://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader"), contains("MyEnreplacedyValue", "MyInterceptorValue"));
verify(response).close();
}
// SPR-15066
@Test
public void requestInterceptorCanAddExistingHeaderValueWithBody() throws Exception {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
request.getHeaders().add("MyHeader", "MyInterceptorValue");
return execution.execute(request, body);
};
template.setInterceptors(Collections.singletonList(interceptor));
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.clreplaced, contentType)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
mockSentRequest(POST, "http://example.com", requestHeaders);
mockResponseStatus(HttpStatus.OK);
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(contentType);
enreplacedyHeaders.add("MyHeader", "MyEnreplacedyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<>("Hello World", enreplacedyHeaders);
template.exchange("http://example.com", POST, enreplacedy, Void.clreplaced);
replacedertThat(requestHeaders.get("MyHeader"), contains("MyEnreplacedyValue", "MyInterceptorValue"));
verify(response).close();
}
private void mockSentRequest(HttpMethod method, String uri) throws Exception {
mockSentRequest(method, uri, new HttpHeaders());
}
private void mockSentRequest(HttpMethod method, String uri, HttpHeaders requestHeaders) throws Exception {
given(requestFactory.createRequest(new URI(uri), method)).willReturn(request);
given(request.getHeaders()).willReturn(requestHeaders);
}
private void mockResponseStatus(HttpStatus responseStatus) throws Exception {
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(responseStatus.isError());
given(response.getStatusCode()).willReturn(responseStatus);
given(response.getRawStatusCode()).willReturn(responseStatus.value());
given(response.getStatusText()).willReturn(responseStatus.getReasonPhrase());
}
private void mockTextPlainHttpMessageConverter() {
mockHttpMessageConverter(MediaType.TEXT_PLAIN, String.clreplaced);
}
private void mockHttpMessageConverter(MediaType mediaType, Clreplaced type) {
given(converter.canRead(type, null)).willReturn(true);
given(converter.canRead(type, mediaType)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
given(converter.canRead(type, mediaType)).willReturn(true);
given(converter.canWrite(type, null)).willReturn(true);
given(converter.canWrite(type, mediaType)).willReturn(true);
}
private void mockTextResponseBody(String expectedBody) throws Exception {
mockResponseBody(expectedBody, MediaType.TEXT_PLAIN);
}
private void mockResponseBody(String expectedBody, MediaType mediaType) throws Exception {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(mediaType);
responseHeaders.setContentLength(expectedBody.length());
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expectedBody.getBytes()));
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expectedBody);
}
}
18
View Source File : AbstractRequestExpectationManager.java
License : MIT License
Project Creator : mindcarver
License : MIT License
Project Creator : mindcarver
@SuppressWarnings("deprecation")
@Override
public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
RequestExpectation expectation = null;
synchronized (this.requests) {
if (this.requests.isEmpty()) {
afterExpectationsDeclared();
}
try {
// Try this first for backwards compatibility
ClientHttpResponse response = validateRequestInternal(request);
if (response != null) {
return response;
} else {
expectation = matchRequest(request);
}
} finally {
this.requests.add(request);
}
}
return expectation.createResponse(request);
}
18
View Source File : RestTemplateTests.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* @author Arjen Poutsma
*/
@SuppressWarnings("unchecked")
public clreplaced RestTemplateTests {
private RestTemplate template;
private ClientHttpRequestFactory requestFactory;
private ClientHttpRequest request;
private ClientHttpResponse response;
private ResponseErrorHandler errorHandler;
@SuppressWarnings("rawtypes")
private HttpMessageConverter converter;
@Before
public void setUp() {
requestFactory = mock(ClientHttpRequestFactory.clreplaced);
request = mock(ClientHttpRequest.clreplaced);
response = mock(ClientHttpResponse.clreplaced);
errorHandler = mock(ResponseErrorHandler.clreplaced);
converter = mock(HttpMessageConverter.clreplaced);
template = new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
template.setRequestFactory(requestFactory);
template.setErrorHandler(errorHandler);
}
@Test
public void varArgsTemplateVariables() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/21"), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.execute("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21");
verify(response).close();
}
@Test
public void varArgsNullTemplateVariable() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, null, "foo");
verify(response).close();
}
@Test
public void mapTemplateVariables() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/42"), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Map<String, String> vars = Collections.singletonMap("hotel", "42");
template.execute("http://example.com/hotels/{hotel}/bookings/{hotel}", HttpMethod.GET, null, null, vars);
verify(response).close();
}
@Test
public void mapNullTemplateVariable() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Map<String, String> vars = new HashMap<String, String>(2);
vars.put("first", null);
vars.put("last", "foo");
template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, vars);
verify(response).close();
}
@Test
public void errorHandling() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(true);
given(response.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR);
given(response.getStatusText()).willReturn("Internal Server Error");
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).given(errorHandler).handleError(response);
try {
template.execute("http://example.com", HttpMethod.GET, null, null);
fail("HttpServerErrorException expected");
} catch (HttpServerErrorException ex) {
// expected
}
verify(response).close();
}
@Test
public void getForObject() throws Exception {
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType textPlain = new MediaType("text", "plain");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
String expected = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
given(converter.canRead(String.clreplaced, textPlain)).willReturn(true);
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
String result = template.getForObject("http://example.com", String.clreplaced);
replacedertEquals("Invalid GET result", expected, result);
replacedertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void getUnsupportedMediaType() throws Exception {
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType supportedMediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType));
given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = new MediaType("bar", "baz");
responseHeaders.setContentType(contentType);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream("Foo".getBytes()));
given(converter.canRead(String.clreplaced, contentType)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
try {
template.getForObject("http://example.com/{p}", String.clreplaced, "resource");
fail("UnsupportedMediaTypeException expected");
} catch (RestClientException ex) {
// expected
}
verify(response).close();
}
@Test
public void getForEnreplacedy() throws Exception {
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType textPlain = new MediaType("text", "plain");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
String expected = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
given(converter.canRead(String.clreplaced, textPlain)).willReturn(true);
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
ResponseEnreplacedy<String> result = template.getForEnreplacedy("http://example.com", String.clreplaced);
replacedertEquals("Invalid GET result", expected, result.getBody());
replacedertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid Content-Type header", textPlain, result.getHeaders().getContentType());
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
DefaultUriTemplateHandler uriTemplateHandler = new DefaultUriTemplateHandler();
uriTemplateHandler.setParsePath(true);
template.setUriTemplateHandler(uriTemplateHandler);
URI expectedUri = new URI("http://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
given(requestFactory.createRequest(expectedUri, HttpMethod.GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(new HttpHeaders());
given(response.getBody()).willReturn(null);
Map<String, String> uriVariables = new HashMap<String, String>(2);
uriVariables.put("hotel", "1");
uriVariables.put("publicpath", "pics/logo.png");
uriVariables.put("scale", "150x150");
String url = "http://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
template.getForObject(url, String.clreplaced, uriVariables);
verify(response).close();
}
@Test
public void headForHeaders() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.HEAD)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders result = template.headForHeaders("http://example.com");
replacedertSame("Invalid headers returned", responseHeaders, result);
verify(response).close();
}
@Test
public void postForLocation() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
URI result = template.postForLocation("http://example.com", helloWorld);
replacedertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyContentType() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.clreplaced, contentType)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
converter.write(helloWorld, contentType, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.setContentType(contentType);
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<String>(helloWorld, enreplacedyHeaders);
URI result = template.postForLocation("http://example.com", enreplacedy);
replacedertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEnreplacedyCustomHeader() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> enreplacedy = new HttpEnreplacedy<String>(helloWorld, enreplacedyHeaders);
URI result = template.postForLocation("http://example.com", enreplacedy);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader"));
verify(response).close();
}
@Test
public void postForLocationNoLocation() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
URI result = template.postForLocation("http://example.com", helloWorld);
replacedertNull("Invalid POST result", result);
verify(response).close();
}
@Test
public void postForLocationNull() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.postForLocation("http://example.com", null);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForObject() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
converter.write(request, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.clreplaced, textPlain)).willReturn(true);
given(converter.read(eq(Integer.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Integer result = template.postForObject("http://example.com", request, Integer.clreplaced);
replacedertEquals("Invalid POST result", expected, result);
replacedertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void postForEnreplacedy() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
converter.write(request, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.clreplaced, textPlain)).willReturn(true);
given(converter.read(eq(Integer.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
ResponseEnreplacedy<Integer> result = template.postForEnreplacedy("http://example.com", request, Integer.clreplaced);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void postForObjectNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(converter.canRead(Integer.clreplaced, textPlain)).willReturn(true);
given(converter.read(Integer.clreplaced, response)).willReturn(null);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Integer result = template.postForObject("http://example.com", null, Integer.clreplaced);
replacedertNull("Invalid POST result", result);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForEnreplacedyNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(converter.canRead(Integer.clreplaced, textPlain)).willReturn(true);
given(converter.read(Integer.clreplaced, response)).willReturn(null);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
ResponseEnreplacedy<Integer> result = template.postForEnreplacedy("http://example.com", null, Integer.clreplaced);
replacedertFalse("Invalid POST result", result.hasBody());
replacedertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void put() throws Exception {
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).willReturn(request);
String helloWorld = "Hello World";
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.put("http://example.com", helloWorld);
verify(response).close();
}
@Test
public void putNull() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.put("http://example.com", null);
replacedertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void delete() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.DELETE)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.delete("http://example.com");
verify(response).close();
}
@Test
public void optionsForAllow() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.OPTIONS)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST);
responseHeaders.setAllow(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Set<HttpMethod> result = template.optionsForAllow("http://example.com");
replacedertEquals("Invalid OPTIONS result", expected, result);
verify(response).close();
}
@Test
public void ioException() throws Exception {
given(converter.canRead(String.clreplaced, null)).willReturn(true);
MediaType mediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willThrow(new IOException());
try {
template.getForObject("http://example.com/resource", String.clreplaced);
fail("RestClientException expected");
} catch (ResourceAccessException ex) {
// expected
}
}
@Test
public void exchange() throws Exception {
given(converter.canRead(Integer.clreplaced, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
String body = "Hello World";
converter.write(body, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.clreplaced, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(Integer.clreplaced, response)).willReturn(expected);
given(converter.read(eq(Integer.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<String>(body, enreplacedyHeaders);
ResponseEnreplacedy<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEnreplacedy, Integer.clreplaced);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.clreplaced);
template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {
};
given(converter.canRead(intList.getType(), null, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
given(converter.canWrite(String.clreplaced, null)).willReturn(true);
String requestBody = "Hello World";
converter.write(requestBody, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
List<Integer> expected = Collections.singletonList(42);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(new Integer(42).toString().getBytes()));
given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.clreplaced))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders enreplacedyHeaders = new HttpHeaders();
enreplacedyHeaders.set("MyHeader", "MyValue");
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<String>(requestBody, enreplacedyHeaders);
ResponseEnreplacedy<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEnreplacedy, intList);
replacedertEquals("Invalid POST result", expected, result.getBody());
replacedertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
replacedertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
replacedertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
replacedertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
}
18
View Source File : SpringRestTemplateAdvice.java
License : Apache License 2.0
Project Creator : elastic
License : Apache License 2.0
Project Creator : elastic
@Nullable
@Advice.OnMethodEnter(suppress = Throwable.clreplaced, inline = false)
public static Object beforeExecute(@Advice.This ClientHttpRequest request) {
logger.trace("Enter advice for method {}#execute()", request.getClreplaced().getName());
final AbstractSpan<?> parent = TracerAwareInstrumentation.tracer.getActive();
if (parent == null) {
return null;
}
URI uri = request.getURI();
Span span = HttpClientHelper.startHttpClientSpan(parent, Objects.toString(request.getMethod()), uri, uri.getHost());
if (span != null) {
span.activate();
span.propagateTraceContext(request, SpringRestRequestHeaderSetter.INSTANCE);
return span;
}
return null;
}
17
View Source File : RootUriRequestExpectationManagerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() throws Exception {
ClientHttpRequest request = mock(ClientHttpRequest.clreplaced);
given(request.getURI()).willReturn(new URI(this.uri + "/hello"));
this.manager.validateRequest(request);
verify(this.delegate).validateRequest(this.requestCaptor.capture());
HttpRequestWrapper actual = (HttpRequestWrapper) this.requestCaptor.getValue();
replacedertThat(actual.getRequest()).isSameAs(request);
replacedertThat(actual.getURI()).isEqualTo(new URI("/hello"));
}
See More Examples