org.springframework.http.client.ClientHttpRequest Java Examples

The following examples show how to use org.springframework.http.client.ClientHttpRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserJwtSsoTokenRestTemplate.java    From wecube-platform with Apache License 2.0 7 votes vote down vote up
@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;
}
 
Example #2
Source File: AbstractRequestExpectationManager.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #3
Source File: RestTemplateBuilder.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Create the {@link RestTemplate} to use.
 * @return the {@link RestTemplate} to use.
 */
protected RestTemplate createTemplate() {

	ClientHttpRequestFactory requestFactory = this.requestFactory.get();

	LinkedHashMap<String, String> defaultHeaders = new LinkedHashMap<>(this.defaultHeaders);
	LinkedHashSet<RestTemplateRequestCustomizer<ClientHttpRequest>> requestCustomizers = new LinkedHashSet<>(
			this.requestCustomizers);

	RestTemplate restTemplate = VaultClients.createRestTemplate(this.endpointProvider,
			new RestTemplateBuilderClientHttpRequestFactoryWrapper(requestFactory, requestCustomizers));

	restTemplate.getInterceptors().add((httpRequest, bytes, clientHttpRequestExecution) -> {

		HttpHeaders headers = httpRequest.getHeaders();
		defaultHeaders.forEach((key, value) -> {
			if (!headers.containsKey(key)) {
				headers.add(key, value);
			}
		});

		return clientHttpRequestExecution.execute(httpRequest, bytes);
	});

	return restTemplate;
}
 
Example #4
Source File: CloudControllerRestClientHttpRequestFactory.java    From cf-java-client-sap with Apache License 2.0 6 votes vote down vote up
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    ClientHttpRequest request = delegate.createRequest(uri, httpMethod);

    String authorizationHeader = oAuthClient.getAuthorizationHeader();
    if (authorizationHeader != null) {
        request.getHeaders()
               .add(AUTHORIZATION_HEADER_KEY, authorizationHeader);
    }

    if (credentials != null && credentials.getProxyUser() != null) {
        request.getHeaders()
               .add(PROXY_USER_HEADER_KEY, credentials.getProxyUser());
    }

    return request;
}
 
Example #5
Source File: AsyncRestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void doWithRequest(final AsyncClientHttpRequest request) throws IOException {
	if (this.adaptee != null) {
		this.adaptee.doWithRequest(new ClientHttpRequest() {
			@Override
			public ClientHttpResponse execute() throws IOException {
				throw new UnsupportedOperationException("execute not supported");
			}
			@Override
			public OutputStream getBody() throws IOException {
				return request.getBody();
			}
			@Override
			public HttpMethod getMethod() {
				return request.getMethod();
			}
			@Override
			public URI getURI() {
				return request.getURI();
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		});
	}
}
 
Example #6
Source File: HttpAccessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: AsyncRestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doWithRequest(final AsyncClientHttpRequest request) throws IOException {
	if (this.adaptee != null) {
		this.adaptee.doWithRequest(new ClientHttpRequest() {
			@Override
			public ClientHttpResponse execute() throws IOException {
				throw new UnsupportedOperationException("execute not supported");
			}
			@Override
			public OutputStream getBody() throws IOException {
				return request.getBody();
			}
			@Override
			public HttpMethod getMethod() {
				return request.getMethod();
			}
			@Override
			public URI getURI() {
				return request.getURI();
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		});
	}
}
 
Example #8
Source File: RestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
	if (this.responseType != null) {
		Class<?> responseClass = null;
		if (this.responseType instanceof Class) {
			responseClass = (Class<?>) this.responseType;
		}
		List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
		for (HttpMessageConverter<?> converter : getMessageConverters()) {
			if (responseClass != null) {
				if (converter.canRead(responseClass, null)) {
					allSupportedMediaTypes.addAll(getSupportedMediaTypes(converter));
				}
			}
			else if (converter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
				if (genericConverter.canRead(this.responseType, null, null)) {
					allSupportedMediaTypes.addAll(getSupportedMediaTypes(converter));
				}
			}
		}
		if (!allSupportedMediaTypes.isEmpty()) {
			MediaType.sortBySpecificity(allSupportedMediaTypes);
			if (logger.isDebugEnabled()) {
				logger.debug("Setting request Accept header to " + allSupportedMediaTypes);
			}
			request.getHeaders().setAccept(allSupportedMediaTypes);
		}
	}
}
 
Example #9
Source File: RestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "'url' must not be null");
	Assert.notNull(method, "'method' must not be null");
	ClientHttpResponse response = null;
	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);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example #10
Source File: RestTemplateFactory.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
    HttpHeaders requestHeaders = request.getHeaders();
    if (!requestHeaders.containsKey(HttpHeaders.AUTHORIZATION)) {
        requestHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + computeAuthorizationToken());
    }
    return request;
}
 
Example #11
Source File: AbstractRequestExpectationManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example #12
Source File: CseRequestCallback.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
  orgCallback.doWithRequest(request);
  CseClientHttpRequest req = (CseClientHttpRequest) request;
  req.setResponseType(overrideResponseType());

  if (!CseHttpEntity.class.isInstance(requestBody)) {
    return;
  }

  CseHttpEntity<?> entity = (CseHttpEntity<?>) requestBody;
  req.setContext(entity.getContext());
}
 
Example #13
Source File: ContentRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 new RequestMatcher() {
		@Override
		public void match(ClientHttpRequest request) throws IOException, AssertionError {
			MediaType actualContentType = request.getHeaders().getContentType();
			assertTrue("Content type not set", actualContentType != null);
			assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]",
					actualContentType.isCompatibleWith(contentType));
		}
	};
}
 
Example #14
Source File: MockRestRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Assert request header values with the given Hamcrest matcher.
 */
@SuppressWarnings("unchecked")
public static RequestMatcher header(final String name, final Matcher<? super String>... matchers) {
	return new RequestMatcher() {
		@Override
		public void match(ClientHttpRequest request) {
			assertHeaderValueCount(name, request.getHeaders(), matchers.length);
			for (int i = 0 ; i < matchers.length; i++) {
				assertThat("Request header", request.getHeaders().get(name).get(i), matchers[i]);
			}
		}
	};
}
 
Example #15
Source File: ContentRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Assert the request content type as a {@link MediaType}.
 */
public RequestMatcher contentType(final MediaType expectedContentType) {
	return new RequestMatcher() {
		@Override
		public void match(ClientHttpRequest request) throws IOException, AssertionError {
			MediaType actualContentType = request.getHeaders().getContentType();
			assertTrue("Content type not set", actualContentType != null);
			assertEquals("Content type", expectedContentType, actualContentType);
		}
	};
}
 
Example #16
Source File: UnorderedRequestExpectationManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
private ClientHttpRequest createRequest(HttpMethod method, String url) {
	try {
		return new org.springframework.mock.http.client.MockAsyncClientHttpRequest(method,  new URI(url));
	}
	catch (URISyntaxException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #17
Source File: RestTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
		@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "URI is required");
	Assert.notNull(method, "HttpMethod is required");
	ClientHttpResponse response = null;
	try {
		ClientHttpRequest request = createRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		response = request.execute();
		handleResponse(url, method, response);
		return (responseExtractor != null ? responseExtractor.extractData(response) : 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);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example #18
Source File: AbstractRequestExpectationManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return a matching expectation, or {@code null} if none match.
 */
@Nullable
public RequestExpectation findExpectation(ClientHttpRequest request) throws IOException {
	for (RequestExpectation expectation : this.expectations) {
		try {
			expectation.match(request);
			return expectation;
		}
		catch (AssertionError error) {
			// We're looking to find a match or return null..
		}
	}
	return null;
}
 
Example #19
Source File: ContentRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Compare the body of the request to the given byte array.
 */
public RequestMatcher bytes(final byte[] expectedContent) {
	return new RequestMatcher() {
		@Override
		public void match(ClientHttpRequest request) throws IOException, AssertionError {
			MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
			assertEquals("Request content", expectedContent, mockRequest.getBodyAsBytes());
		}
	};
}
 
Example #20
Source File: UnorderedRequestExpectationManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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;
}
 
Example #21
Source File: XpathRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public final void match(ClientHttpRequest request) throws IOException, AssertionError {
	try {
		MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
		matchInternal(mockRequest);
	}
	catch (Exception e) {
		throw new AssertionError("Failed to parse XML request content: " + e.getMessage());
	}
}
 
Example #22
Source File: MockRestRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Expect a request to the given URI.
 * @param uri the expected URI
 * @return the request matcher
 */
public static RequestMatcher requestTo(final URI uri) {
	Assert.notNull(uri, "'uri' must not be null");
	return new RequestMatcher() {
		@Override
		public void match(ClientHttpRequest request) throws IOException, AssertionError {
			AssertionErrors.assertEquals("Unexpected request", uri, request.getURI());
		}
	};
}
 
Example #23
Source File: ContentRequestMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Get the body of the request as a UTF-8 string and appply the given {@link Matcher}.
 */
public RequestMatcher string(final Matcher<? super String> matcher) {
	return new RequestMatcher() {
		@Override
		public void match(ClientHttpRequest request) throws IOException, AssertionError {
			MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
			assertThat("Request content", mockRequest.getBodyAsString(), matcher);
		}
	};
}
 
Example #24
Source File: XpathRequestMatchers.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public final void match(ClientHttpRequest request) throws IOException, AssertionError {
	try {
		MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
		matchInternal(mockRequest);
	}
	catch (Exception ex) {
		throw new AssertionError("Failed to parse XML request content", ex);
	}
}
 
Example #25
Source File: BasicAuthRestTemplate.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
    request.getHeaders().putAll(getRequestHttpHeaders());

    if (null != targetRequestCallback) {
        targetRequestCallback.doWithRequest(request);
    }
}
 
Example #26
Source File: BasicAuthorizationInterceptorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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"));
}
 
Example #27
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	requestFactory = mock(ClientHttpRequestFactory.class);
	request = mock(ClientHttpRequest.class);
	response = mock(ClientHttpResponse.class);
	errorHandler = mock(ResponseErrorHandler.class);
	converter = mock(HttpMessageConverter.class);
	template = new RestTemplate(Collections.singletonList(converter));
	template.setRequestFactory(requestFactory);
	template.setErrorHandler(errorHandler);
}
 
Example #28
Source File: DiscordHttpRequestFactory.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #29
Source File: ConfigServicePropertySourceLocatorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void failFast() throws Exception {
	ClientHttpRequestFactory requestFactory = Mockito
			.mock(ClientHttpRequestFactory.class);
	ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
	ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
	Mockito.when(requestFactory.createRequest(Mockito.any(URI.class),
			Mockito.any(HttpMethod.class))).thenReturn(request);
	RestTemplate restTemplate = new RestTemplate(requestFactory);
	ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
	defaults.setFailFast(true);
	this.locator = new ConfigServicePropertySourceLocator(defaults);
	Mockito.when(request.getHeaders()).thenReturn(new HttpHeaders());
	Mockito.when(request.execute()).thenReturn(response);
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON);
	Mockito.when(response.getHeaders()).thenReturn(headers);
	Mockito.when(response.getStatusCode())
			.thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
	Mockito.when(response.getBody())
			.thenReturn(new ByteArrayInputStream("{}".getBytes()));
	this.locator.setRestTemplate(restTemplate);
	this.expected
			.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
	this.expected.expectMessage("fail fast property is set");
	this.locator.locateCollection(this.environment);
}
 
Example #30
Source File: RestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
		@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "URI is required");
	Assert.notNull(method, "HttpMethod is required");
	ClientHttpResponse response = null;
	try {
		ClientHttpRequest request = createRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		response = request.execute();
		handleResponse(url, method, response);
		return (responseExtractor != null ? responseExtractor.extractData(response) : 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);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}