private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath) throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); ClientHttpRequest request = clientHttpRequestFactory.createRequest( new URI("http://localhost:" + context.getEmbeddedServletContainer().getPort() + resourcePath), HttpMethod.GET); ClientHttpResponse response = request.execute(); try { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); assertThat(actual).isEqualTo("Hello World"); } finally { response.close(); } }
private static void loginAndSaveJsessionIdCookie(final String user, final String password, final HttpHeaders headersToUpdate) { String url = "http://localhost:" + port + "/"; new RestTemplate().execute(url, HttpMethod.POST, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest request) throws IOException { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("username", user); map.add("password", password); new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request); } }, new ResponseExtractor<Object>() { @Override public Object extractData(ClientHttpResponse response) throws IOException { headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie")); return null; } }); }
@Override public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException { String uri = request.getURI().toString(); if (uri.startsWith(this.rootUri)) { uri = uri.substring(this.rootUri.length()); request = new ReplaceUriClientHttpRequest(uri, request); } try { return this.expectationManager.validateRequest(request); } catch (AssertionError ex) { String message = ex.getMessage(); String prefix = "Request URI expected:</"; if (message != null && message.startsWith(prefix)) { throw new AssertionError("Request URI expected:<" + this.rootUri + message.substring(prefix.length() - 1)); } throw ex; } }
@Override public void onApplicationEvent(ClassPathChangedEvent event) { try { ClassLoaderFiles classLoaderFiles = getClassLoaderFiles(event); ClientHttpRequest request = this.requestFactory.createRequest(this.uri, HttpMethod.POST); byte[] bytes = serialize(classLoaderFiles); HttpHeaders headers = request.getHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentLength(bytes.length); FileCopyUtils.copy(bytes, request.getBody()); logUpload(classLoaderFiles); ClientHttpResponse response = request.execute(); Assert.state(response.getStatusCode() == HttpStatus.OK, "Unexpected " + response.getStatusCode() + " response uploading class files"); } catch (IOException ex) { throw new IllegalStateException(ex); } }
private ClientHttpRequest createRequest(String url) throws IOException{ URL u; // quick fix for that URLs from konachan.net API does not contain protocol if (url.startsWith("//")){ url = "http:" + url; } if (forceHttps){ u = new URL(url.replace("http:", "https:")); }else{ u = new URL(url); } try{ ClientHttpRequest request = requestFactory.createRequest(u.toURI(), HttpMethod.GET); logger.info("start downloading: {}", u); return request; }catch (URISyntaxException ex){ throw new RuntimeException(ex); } }
public byte[] download(String url){ for (int retryCount = 0; retryCount < maxRetryCount; retryCount++){ try{ ClientHttpRequest request = createRequest(url); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (ClientHttpResponse response = request.execute()){ responseRefs.add(new WeakReference<>(response, referenceQueue)); InputStream input = response.getBody(); IOUtils.copy(input, output); } return output.toByteArray(); }catch (IOException ex){ if (ex instanceof SocketException && closed){ return null; } logger.info("IO异常,重试", ex); } } logger.info("到达最大重试次数,已放弃重试"); return null; }
private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath) throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); ClientHttpRequest request = clientHttpRequestFactory.createRequest( new URI("http://localhost:" + context.getEmbeddedServletContainer().getPort() + resourcePath), HttpMethod.GET); ClientHttpResponse response = request.execute(); try { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); assertThat(actual, equalTo("Hello World")); } finally { response.close(); } }
/** * @param uri Set the uri * @param httpMethod set the httpMethod * @return a client http request object * @throws IOException if there is a problem */ public final ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException { if (proxyHost != null && proxyPort != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( proxyHost, proxyPort)); super.setProxy(proxy); } ClientHttpRequest clientHttpRequest = super.createRequest(uri, httpMethod); String unencoded = username + ":" + password; String encoded = new String(Base64.encodeBase64(unencoded.getBytes())); clientHttpRequest.getHeaders().add("Authorization", "Basic " + encoded); return clientHttpRequest; }
/** * @param uri Set the uri * @param httpMethod set the httpMethod * @return a client http request object * @throws IOException if there is a problem */ public final ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException { ClientHttpRequest clientHttpRequest = super.createRequest(uri, httpMethod); SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext != null && securityContext.getAuthentication() != null) { Authentication authentication = securityContext.getAuthentication(); if (authentication != null && authentication.getPrincipal() != null && authentication.getPrincipal().getClass() .equals(User.class)) { User user = (User) authentication.getPrincipal(); String unencoded = user.getUsername() + ":" + user.getPassword(); String encoded = new String(Base64.encodeBase64(unencoded.getBytes())); clientHttpRequest.getHeaders().add("Authorization", "Basic " + encoded); } } return clientHttpRequest; }
public void doWithRequest(ClientHttpRequest request) throws IOException { if (responseType != null) { List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); for (HttpMessageConverter<?> messageConverter : getMessageConverters()) { if (messageConverter.canRead(responseType, null)) { List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes(); for (MediaType supportedMediaType : supportedMediaTypes) { if (supportedMediaType.getCharSet() != null) { supportedMediaType = new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype()); } allSupportedMediaTypes.add(supportedMediaType); } } } if (!allSupportedMediaTypes.isEmpty()) { MediaType.sortBySpecificity(allSupportedMediaTypes); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Setting request Accept header to " + allSupportedMediaTypes); } request.getHeaders().setAccept(allSupportedMediaTypes); } } }
@Override @SuppressWarnings("deprecation") public ClientHttpRequest createRequest(URI originalUri, HttpMethod httpMethod) throws IOException { String serviceId = originalUri.getHost(); ServiceInstance instance = loadBalancer.choose(serviceId); if (instance == null) { throw new IllegalStateException("No instances available for " + serviceId); } URI uri = loadBalancer.reconstructURI(instance, originalUri); IClientConfig clientConfig = clientFactory.getClientConfig(instance.getServiceId()); RestClient client = clientFactory.getClient(instance.getServiceId(), RestClient.class); HttpRequest request = HttpRequest.newBuilder() .uri(uri) .verb(HttpRequest.Verb.valueOf(httpMethod.name())) .build(); return new RibbonHttpRequest(request, client, clientConfig); }
@Test public void userInfoLoadBalancedNoRetry() throws Exception { this.context = new SpringApplicationBuilder(ClientConfiguration.class) .properties("spring.config.name=test", "server.port=0", "security.oauth2.resource.userInfoUri:http://nosuchservice", "security.oauth2.resource.loadBalanced=true") .run(); assertTrue(this.context.containsBean("loadBalancedUserInfoRestTemplateCustomizer")); assertFalse(this.context.containsBean("retryLoadBalancedUserInfoRestTemplateCustomizer")); OAuth2RestTemplate template = this.context .getBean(UserInfoRestTemplateFactory.class).getUserInfoRestTemplate(); ClientHttpRequest request = template.getRequestFactory() .createRequest(new URI("http://nosuchservice"), HttpMethod.GET); expected.expectMessage("No instances available for nosuchservice"); request.execute(); }
private void setHeaders(ClientHttpRequest request, List<String> headersList) { for (String headerAsString : headersList) { if (StringUtils.isEmpty(headerAsString)) { continue; } int i = headerAsString.indexOf(':'); if (i < 0) { throw new IllegalArgumentException("Illegal header specification (expected was 'name: value' pair): " + headerAsString); } String headerName = headerAsString.substring(0, i); int headerValueIndex; if (i+1 == headerAsString.length() || headerAsString.charAt(i+1) != ' ') { // let's be nice and treat well the wrong case (there's no space after ':') headerValueIndex = i+1; } else { // correct case: ':' followed by space headerValueIndex = i+2; } String headerValue = headerAsString.substring(headerValueIndex); request.getHeaders().add(headerName, headerValue); } }
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { Assert.notNull(uri, "'uri' must not be null"); Assert.notNull(httpMethod, "'httpMethod' must not be null"); if (this.requestIterator == null) { this.requestIterator = MockRestServiceServer.this.expectedRequests.iterator(); } if (!this.requestIterator.hasNext()) { throw new AssertionError("No further requests expected"); } RequestMatcherClientHttpRequest request = this.requestIterator.next(); request.setURI(uri); request.setMethod(httpMethod); MockRestServiceServer.this.actualRequests.add(request); return request; }
@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.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) { tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified. } request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue())); }
@Test public void failFastWhenBothPasswordAndAuthorizationPropertiesSet() throws Exception { ClientHttpRequestFactory requestFactory = Mockito .mock(ClientHttpRequestFactory.class); ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class); Mockito.when( requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class))).thenReturn(request); ConfigClientProperties defaults = new ConfigClientProperties(this.environment); defaults.setFailFast(true); defaults.setUsername("username"); defaults.setPassword("password"); defaults.setAuthorization("Basic dXNlcm5hbWU6cGFzc3dvcmQNCg=="); this.locator = new ConfigServicePropertySourceLocator(defaults); this.expected.expect(IllegalStateException.class); this.expected.expectMessage("You must set either 'password' or 'authorization'"); this.locator.locate(this.environment); }
@Test public void interceptorShouldAddHeaderWhenPasswordPropertySet() throws Exception { ClientHttpRequestFactory requestFactory = Mockito .mock(ClientHttpRequestFactory.class); ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class); Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class))).thenReturn(request); ConfigClientProperties defaults = new ConfigClientProperties(this.environment); defaults.setUsername("username"); defaults.setPassword("password"); this.locator = new ConfigServicePropertySourceLocator(defaults); RestTemplate restTemplate = ReflectionTestUtils.invokeMethod(this.locator, "getSecureRestTemplate", defaults); restTemplate.setRequestFactory(requestFactory); this.locator.setRestTemplate(restTemplate); this.locator.locate(this.environment); assertThat(restTemplate.getInterceptors()).hasSize(1); }
@Test public void interceptorShouldAddHeaderWhenAuthorizationPropertySet() throws Exception { ClientHttpRequestFactory requestFactory = Mockito .mock(ClientHttpRequestFactory.class); ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class); Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class))).thenReturn(request); ConfigClientProperties defaults = new ConfigClientProperties(this.environment); defaults.setAuthorization("Basic dXNlcm5hbWU6cGFzc3dvcmQ="); this.locator = new ConfigServicePropertySourceLocator(defaults); RestTemplate restTemplate = ReflectionTestUtils.invokeMethod(this.locator, "getSecureRestTemplate", defaults); restTemplate.setRequestFactory(requestFactory); this.locator.setRestTemplate(restTemplate); this.locator.locate(this.environment); assertThat(restTemplate.getInterceptors()).hasSize(1); }
@SuppressWarnings("unchecked") @Override public void doWithRequest(ClientHttpRequest httpRequest) throws IOException { httpRequest.getHeaders().setAccept(mediaTypes); T requestBody = requestEntity.getBody(); Class<?> requestType = requestBody.getClass(); HttpHeaders requestHeaders = requestEntity.getHeaders(); MediaType requestContentType = requestHeaders.getContentType(); for (HttpMessageConverter<?> messageConverter : restTemplate.getMessageConverters()) { if (messageConverter.canWrite(requestType, requestContentType)) { if (!requestHeaders.isEmpty()) { httpRequest.getHeaders().putAll(requestHeaders); } ((HttpMessageConverter<Object>) messageConverter).write(requestBody, requestContentType, httpRequest); return; } } }
@SuppressWarnings("unchecked") public void doWithRequest(ClientHttpRequest request) throws IOException { if (responseType != null) { List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); for (HttpMessageConverter<?> messageConverter : template.getMessageConverters()) { if (messageConverter.canRead(responseType, null)) { List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes(); for (MediaType supportedMediaType : supportedMediaTypes) { if (supportedMediaType.getCharSet() != null) { supportedMediaType = new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype()); } allSupportedMediaTypes.add(supportedMediaType); } } } if (!allSupportedMediaTypes.isEmpty()) { MediaType.sortBySpecificity(allSupportedMediaTypes); request.getHeaders().setAccept(allSupportedMediaTypes); } } }
@Override protected ClientHttpRequest createRequest(URI uri, HttpMethod method) throws IOException { OAuth2AccessToken accessToken = getAccessToken(); AuthenticationScheme authenticationScheme = resource.getAuthenticationScheme(); if (AuthenticationScheme.query.equals(authenticationScheme) || AuthenticationScheme.form.equals(authenticationScheme)) { uri = appendQueryParameter(uri, accessToken); } ClientHttpRequest req = super.createRequest(uri, method); if (AuthenticationScheme.header.equals(authenticationScheme)) { authenticator.authenticate(resource, getOAuth2ClientContext(), req); } return req; }
@Test public void testRetryAccessDeniedException() throws Exception { final AtomicBoolean failed = new AtomicBoolean(false); restTemplate.getOAuth2ClientContext().setAccessToken(new DefaultOAuth2AccessToken("TEST")); restTemplate.setAccessTokenProvider(new StubAccessTokenProvider()); restTemplate.setRequestFactory(new ClientHttpRequestFactory() { public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { if (!failed.get()) { failed.set(true); throw new AccessTokenRequiredException(resource); } return request; } }); Boolean result = restTemplate.doExecute(new URI("http://foo"), HttpMethod.GET, new NullRequestCallback(), new SimpleResponseExtractor()); assertTrue(result); }
/** * {@inheritDoc} */ @Override public void doWithRequest(ClientHttpRequest request) throws IOException { orgCallback.doWithRequest(request); if (!CseHttpEntity.class.isInstance(requestBody)) { return; } CseClientHttpRequest req = (CseClientHttpRequest) request; CseHttpEntity<?> entity = (CseHttpEntity<?>) requestBody; req.setContext(entity.getContext()); }
@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 (cloudCredentials != null && cloudCredentials.getProxyUser() != null) { request.getHeaders().add(PROXY_USER_HEADER_KEY, cloudCredentials.getProxyUser()); } return request; }
@Test public void testInject() { String url = "http://localhost:4000/foo"; mockServer.expect(MockRestRequestMatchers.requestTo(url)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(new ResponseCreator() { @Override public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException { MockClientHttpResponse response = new MockClientHttpResponse(new byte[1], HttpStatus.OK); response.getHeaders().add("traceId", request.getHeaders() .getFirst("traceId")); response.getHeaders().add("spanId", request.getHeaders() .getFirst("spanId")); return response; } }); ResponseEntity<String> responseEntity = client.getForEntity(url, String.class); List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); Assert.assertEquals(mockSpans.get(0).context().traceId(), Long.parseLong(responseEntity.getHeaders().getFirst("traceId"))); Assert.assertEquals(mockSpans.get(0).context().spanId(), Long.parseLong(responseEntity.getHeaders().getFirst("spanId"))); }
@Before public void setUp() throws Exception { ClientHttpRequestFactory factory = new AbstractClientHttpRequestFactoryWrapper(createClientHttpRequestFactory()) { @Override protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory) throws IOException { myRequestedURIs.add(uri.getPath()); return requestFactory.createRequest(uri, httpMethod); } }; template = new VaultTemplate(vault.getEndpoint(), factory, vault.getSimpleSessionManager()); resolver = new VaultParametersResolver(); feature = new VaultFeatureSettings(vault.getUrl(), "", ""); }
@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; }
private void getOrCreateWorkflowAndAddInteraction(Pact pact, ClientHttpRequest clientRequest, ClientHttpResponse response) throws IOException { String bodyString = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()); response.getBody().reset(); Pact.Interaction interaction = new Pact.Interaction( null, new Pact.InteractionRequest(restRequestDescriptor.getMethod(), urlencode(restRequestDescriptor.getUrl()), clientRequest.getHeaders(), extractBodyContent(restRequestDescriptor.getRequest())), new Pact.InteractionResponse(response.getRawStatusCode(), response.getHeaders(), bodyString, schema), objectConverter); Pact.Workflow workflow = pact.getWorkflow(this.workflowId, this.providerStates); workflow.addInteraction(interaction); }
/** * 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(); if (!getErrorHandler().hasError(response)) { logResponseStatus(method, url, response); } else { handleResponseError(method, url, response); } if (responseExtractor != null) { return responseExtractor.extractData(response); } else { return null; } } catch (IOException ex) { throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + url + "\":" + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } }
@Override public void doWithRequest(ClientHttpRequest request) throws IOException { if (responseType != null) { Class<?> responseClass = null; if (responseType instanceof Class) { responseClass = (Class<?>) 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(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); } } }
@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(); } }); } }
/** * 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; }
private HttpRequest addTokenInURI(HttpRequest request) throws IOException, URISyntaxException{ ClientHttpRequest clientRequest = (ClientHttpRequest) request; List<NameValuePair> params = new ArrayList<>() ; params.add(new BasicNameValuePair("api_key", this.apiKey)); String url = URLEncodedUtils.format(params, "UTF-8"); URI src = new URI(request.getURI().toString().concat("?").concat(url)); clientRequest = new HttpComponentsClientHttpRequestFactory().createRequest(src, request.getMethod()); return clientRequest; }
@Override public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().putAll(getRequestHttpHeaders()); if (null != targetRequestCallback) { targetRequestCallback.doWithRequest(request); } }
@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; }