/** * Assert request header values with the given Hamcrest matcher(s). */ @SafeVarargs public static RequestMatcher header(final String name, final Matcher<? super String>... matchers) { return request -> { assertValueCount("header", name, request.getHeaders(), matchers.length); List<String> headerValues = request.getHeaders().get(name); Assert.state(headerValues != null, "No header values"); for (int i = 0; i < matchers.length; i++) { assertThat("Request header [" + name + "]", headerValues.get(i), matchers[i]); } }; }
/** * Assert request header values. */ public static RequestMatcher header(final String name, final String... expectedValues) { return request -> { assertValueCount("header", name, request.getHeaders(), expectedValues.length); List<String> headerValues = request.getHeaders().get(name); Assert.state(headerValues != null, "No header values"); for (int i = 0; i < expectedValues.length; i++) { assertEquals("Request header [" + name + "]", expectedValues[i], headerValues.get(i)); } }; }
@Override public void doWithRequest(ClientHttpRequest request) throws IOException { if (this.responseType != null) { List<MediaType> allSupportedMediaTypes = getMessageConverters().stream() .filter(converter -> canReadResponse(this.responseType, converter)) .flatMap(this::getSupportedMediaTypes) .distinct() .sorted(MediaType.SPECIFICITY_COMPARATOR) .collect(Collectors.toList()); if (logger.isDebugEnabled()) { logger.debug("Accept=" + allSupportedMediaTypes); } request.getHeaders().setAccept(allSupportedMediaTypes); } }
public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().putAll(this.headers); request.getHeaders().setAccept( Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED)); if (logger.isDebugEnabled()) { logger.debug("Encoding and sending form: " + form); } FORM_MESSAGE_CONVERTER.write(this.form, MediaType.APPLICATION_FORM_URLENCODED, request); } }
/** * Assert the request content type as a {@link MediaType}. */ public RequestMatcher contentType(final MediaType expectedContentType) { return request -> { MediaType actualContentType = request.getHeaders().getContentType(); assertTrue("Content type not set", actualContentType != null); assertEquals("Content type", expectedContentType, actualContentType); }; }
@Override public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().putAll(this.headers); if (this.body != null) { StreamUtils.copy(this.body, SockJsFrame.CHARSET, request.getBody()); } } }
@Override public void doWithRequest(ClientHttpRequest request) throws IOException { if (this.responseType != null) { List<MediaType> allSupportedMediaTypes = getMessageConverters().stream() .filter(converter -> canReadResponse(this.responseType, converter)) .flatMap(this::getSupportedMediaTypes) .distinct() .sorted(MediaType.SPECIFICITY_COMPARATOR) .collect(Collectors.toList()); if (logger.isDebugEnabled()) { logger.debug("Accept=" + allSupportedMediaTypes); } request.getHeaders().setAccept(allSupportedMediaTypes); } }
@Override public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest request) { OAuth2AccessToken accessToken = clientContext.getAccessToken(); if (accessToken == null) { throw new AccessTokenRequiredException(resource); } String tokenType = accessToken.getTokenType(); if (!StringUtils.hasText(tokenType)) { tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified. } else if (tokenType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) { // gh-1346 tokenType = OAuth2AccessToken.BEARER_TYPE; // Ensure we use the correct syntax for the "Bearer" authentication scheme } request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue())); }
/** * Assert the request content type is compatible with the given * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}. */ public RequestMatcher contentTypeCompatibleWith(final MediaType contentType) { return request -> { MediaType actualContentType = request.getHeaders().getContentType(); assertTrue("Content type not set", actualContentType != null); if (actualContentType != null) { assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]", actualContentType.isCompatibleWith(contentType)); } }; }
@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(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(); } }
private HttpHeaders getHttpHeadersWithUserCredentials(ClientHttpRequest request){ return (getHttpHeadersWithUserCredentials(request.getHeaders())); }
@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(); } } }
@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 interceptShouldAddHeader() throws Exception { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET); ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); byte[] body = new byte[] {}; new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body, execution); verify(execution).execute(request, body); assertEquals("Basic c3ByaW5nOmJvb3Q=", request.getHeaders().getFirst("Authorization")); }
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); }
Object requestBody = this.requestEntity.getBody(); if (requestBody == null) { HttpHeaders httpHeaders = httpRequest.getHeaders(); HttpHeaders requestHeaders = this.requestEntity.getHeaders(); if (!requestHeaders.isEmpty()) { Type requestBodyType = (this.requestEntity instanceof RequestEntity ? ((RequestEntity<?>)this.requestEntity).getType() : requestBodyClass); HttpHeaders httpHeaders = httpRequest.getHeaders(); HttpHeaders requestHeaders = this.requestEntity.getHeaders(); MediaType requestContentType = requestHeaders.getContentType();
request.getHeaders().add(headerName, headerValue1); String headerValue2 = "value2"; request.getHeaders().add(headerName, headerValue2); final byte[] body = "Hello World".getBytes("UTF-8"); request.getHeaders().setContentLength(body.length);
String headerName = "MyHeader"; String headerValue1 = "value1"; request.getHeaders().add(headerName, headerValue1); String headerValue2 = "value2"; request.getHeaders().add(headerName, headerValue2); byte[] body = "Hello World".getBytes("UTF-8"); request.getHeaders().setContentLength(body.length); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute();
@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()); } }