@Override protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException { this.request.getHeaders().putAll(headers); StreamUtils.copy(bufferedOutput, this.request.getBody()); ClientHttpResponse response = this.request.execute(); return new BufferingClientHttpResponseWrapper(response); }
@Test public void changeBody() throws Exception { final byte[] changedBody = "Foo".getBytes(); ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { return execution.execute(request, changedBody); } }; requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor)); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); request.execute(); assertTrue(Arrays.equals(changedBody, requestMock.body.toByteArray())); }
@Test(expected = UnsupportedOperationException.class) public void headersAfterExecute() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST); request.getHeaders().add("MyHeader", "value"); byte[] body = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { request.getHeaders().add("MyHeader", "value"); } finally { response.close(); } }
@Override public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException { if (this.iterator.hasNext()) { ClientHttpRequestInterceptor nextInterceptor = this.iterator.next(); return nextInterceptor.intercept(request, body, this); } else { HttpMethod method = request.getMethod(); Assert.state(method != null, "No standard HTTP method"); ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), method); request.getHeaders().forEach((key, value) -> delegate.getHeaders().addAll(key, value)); if (body.length > 0) { if (delegate instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate; streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(body, outputStream)); } else { StreamUtils.copy(body, delegate.getBody()); } } return delegate.execute(); } } }
@Test public void noExecution() throws Exception { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { return responseMock; } }); interceptors.add(new NoOpInterceptor()); requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); ClientHttpResponse response = request.execute(); assertFalse(((NoOpInterceptor) interceptors.get(1)).invoked); assertFalse(requestMock.executed); assertSame(responseMock, response); }
@Test public void changeURI() throws Exception { final URI changedUri = new URI("http://example.com/2"); ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { return execution.execute(new HttpRequestWrapper(request) { @Override public URI getURI() { return changedUri; } }, body); } }; requestFactoryMock = new RequestFactoryMock() { @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { assertEquals(changedUri, uri); return super.createRequest(uri, httpMethod); } }; requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor)); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); request.execute(); }
@Test public void queryParameters() throws Exception { URI uri = new URI(baseUrl + "/params?param1=value¶m2=value1¶m2=value2"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); } finally { response.close(); } }
@Test public void basic() throws Exception { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new NoOpInterceptor()); interceptors.add(new NoOpInterceptor()); interceptors.add(new NoOpInterceptor()); requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); ClientHttpResponse response = request.execute(); assertTrue(((NoOpInterceptor) interceptors.get(0)).invoked); assertTrue(((NoOpInterceptor) interceptors.get(1)).invoked); assertTrue(((NoOpInterceptor) interceptors.get(2)).invoked); assertTrue(requestMock.executed); assertSame(responseMock, response); }
@Test public void changeMethod() throws Exception { final HttpMethod changedMethod = HttpMethod.POST; ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { return execution.execute(new HttpRequestWrapper(request) { @Override public HttpMethod getMethod() { return changedMethod; } }, body); } }; requestFactoryMock = new RequestFactoryMock() { @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { assertEquals(changedMethod, httpMethod); return super.createRequest(uri, httpMethod); } }; requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor)); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); request.execute(); }
@Test public void changeHeaders() throws Exception { final String headerName = "Foo"; final String headerValue = "Bar"; final String otherValue = "Baz"; ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequestWrapper wrapper = new HttpRequestWrapper(request); wrapper.getHeaders().add(headerName, otherValue); return execution.execute(wrapper, body); } }; requestMock = new RequestMock() { @Override public ClientHttpResponse execute() throws IOException { List<String> headerValues = getHeaders().get(headerName); assertEquals(2, headerValues.size()); assertEquals(headerValue, headerValues.get(0)); assertEquals(otherValue, headerValues.get(1)); return super.execute(); } }; requestMock.getHeaders().add(headerName, headerValue); requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor)); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); request.execute(); }
@Test(expected = IllegalStateException.class) public void multipleWrites() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); final byte[] body = "Hello World".getBytes("UTF-8"); if (request instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request; streamingRequest.setBody(outputStream -> { StreamUtils.copy(body, outputStream); outputStream.flush(); outputStream.close(); }); } else { StreamUtils.copy(body, request.getBody()); } request.execute(); FileCopyUtils.copy(body, request.getBody()); }
@Test @Ignore public void largeFileUpload() throws Exception { Random rnd = new Random(); ClientHttpResponse response = null; try { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/post"), HttpMethod.POST); final int BUF_SIZE = 4096; final int ITERATIONS = Integer.MAX_VALUE / BUF_SIZE; // final int contentLength = ITERATIONS * BUF_SIZE; // request.getHeaders().setContentLength(contentLength); OutputStream body = request.getBody(); for (int i = 0; i < ITERATIONS; i++) { byte[] buffer = new byte[BUF_SIZE]; rnd.nextBytes(buffer); body.write(buffer); } response = request.execute(); assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); } finally { if (response != null) { response.close(); } } }
protected void assertHttpMethod(String path, HttpMethod method) throws Exception { ClientHttpResponse response = null; try { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method); if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) { // requires a body try { request.getBody().write(32); } catch (UnsupportedOperationException ex) { // probably a streaming request - let's simply ignore it } } response = request.execute(); assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); assertEquals("Invalid method", path.toUpperCase(Locale.ENGLISH), request.getMethod().name()); } finally { if (response != null) { response.close(); } } }
@Test // SPR-9325, SPR-13860 public void ioException() throws Exception { String url = "http://example.com/resource?access_token=123"; mockSentRequest(GET, url); mockHttpMessageConverter(new MediaType("foo", "bar"), String.class); given(request.execute()).willThrow(new IOException("Socket failure")); try { template.getForObject(url, String.class); fail("RestClientException expected"); } catch (ResourceAccessException ex) { assertEquals("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 status() throws Exception { URI uri = new URI(baseUrl + "/status/notfound"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); assertEquals("Invalid HTTP URI", uri, request.getURI()); ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.NOT_FOUND, response.getStatusCode()); } finally { response.close(); } }
@Test // SPR-8809 public void interceptor() throws Exception { final String headerName = "MyHeader"; final String headerValue = "MyValue"; ClientHttpRequestInterceptor interceptor = (request, body, execution) -> { request.getHeaders().add(headerName, headerValue); return execution.execute(request, body); }; InterceptingClientHttpRequestFactory factory = new InterceptingClientHttpRequestFactory( createRequestFactory(), Collections.singletonList(interceptor)); ClientHttpResponse response = null; try { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.GET); response = request.execute(); assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); HttpHeaders responseHeaders = response.getHeaders(); assertEquals("Custom header invalid", headerValue, responseHeaders.getFirst(headerName)); } finally { if (response != null) { response.close(); } } }
@Test // SPR-15900 public void ioExceptionWithEmptyQueryString() throws Exception { // http://example.com/resource? URI uri = new URI("http", "example.com", "/resource", "", null); given(converter.canRead(String.class, 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.class); fail("RestClientException expected"); } catch (ResourceAccessException ex) { assertEquals("I/O error on GET request for \"http://example.com/resource\": " + "Socket failure; nested exception is java.io.IOException: Socket failure", ex.getMessage()); } }
ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
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()); }
request.getHeaders().setContentLength(body.length); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());