/** * 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; }
@Override protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory) throws IOException { ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod); if (shouldBuffer(uri, httpMethod)) { return new BufferingClientHttpRequestWrapper(request); } else { return request; } }
/** * 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; }
@Override protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory) throws IOException { ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod); if (shouldBuffer(uri, httpMethod)) { return new BufferingClientHttpRequestWrapper(request); } else { return request; } }
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { OAuthSecurityContext context = OAuthSecurityContextHolder.getContext(); if (context == null) { context = new OAuthSecurityContextImpl(); } Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens(); OAuthConsumerToken accessToken = accessTokens == null ? null : accessTokens.get(this.resource.getId()); boolean useAuthHeader = this.resource.isAcceptsAuthorizationHeader(); if (!useAuthHeader) { String queryString = this.support.getOAuthQueryString(this.resource, accessToken, uri.toURL(), httpMethod.name(), this.additionalOAuthParameters); String uriValue = String.valueOf(uri); uri = URI.create((uriValue.contains("?") ? uriValue.substring(0, uriValue.indexOf('?')) : uriValue) + "?" + queryString); } ClientHttpRequest req = delegate.createRequest(uri, httpMethod); if (useAuthHeader) { String authHeader = this.support.getAuthorizationHeader(this.resource, accessToken, uri.toURL(), httpMethod.name(), this.additionalOAuthParameters); req.getHeaders().add("Authorization", authHeader); } Map<String, String> additionalHeaders = this.resource.getAdditionalRequestHeaders(); if (additionalHeaders != null) { for (Map.Entry<String, String> header : additionalHeaders.entrySet()) { req.getHeaders().add(header.getKey(), header.getValue()); } } return req; }
@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 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(); } }
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); }
@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(); } } }
@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 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-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()); } }
protected final ClientHttpRequest createRequest(boolean hasPayload) throws IOException { HttpMethod method = hasPayload ? HttpMethod.POST : HttpMethod.GET; return this.requestFactory.createRequest(this.uri, method); }
private ClientHttpRequest createRequest() throws IOException { return this.requestFactory.createRequest(this.uri, HttpMethod.GET); }
@Test public void echo() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod());
@Test public void repeatableRead() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); String headerName = "MyHeader";
private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) throws IOException { try { while (true) { try { ClientHttpRequest request = this.requestFactory .createRequest(this.uri, HttpMethod.POST); HttpHeaders headers = request.getHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentLength(bytes.length); FileCopyUtils.copy(bytes, request.getBody()); ClientHttpResponse response = request.execute(); HttpStatus statusCode = response.getStatusCode(); Assert.state(statusCode == HttpStatus.OK, () -> "Unexpected " + statusCode + " response uploading class files"); logUpload(classLoaderFiles); return; } catch (ConnectException ex) { logger.warn("Failed to connect when uploading to " + this.uri + ". Upload will be retried in 2 seconds"); Thread.sleep(2000); } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } }