private void init(ApplicationContext ctx) { loadBalancedRestTemplate = new RestTemplate(); SpringClientFactory springClientFactory = springClientFactory(); springClientFactory.setApplicationContext(ctx); loadBalancerClient = new RibbonLoadBalancerClient(springClientFactory); //custom restTemplate LoadBalancerRequestFactory requestFactory = new LoadBalancerRequestFactory(loadBalancerClient, Collections.emptyList()); LoadBalancerInterceptor interceptor = new LoadBalancerInterceptor(loadBalancerClient, requestFactory); List<ClientHttpRequestInterceptor> interceptors = loadBalancedRestTemplate.getInterceptors(); ArrayList<ClientHttpRequestInterceptor> customedInterceptors = new ArrayList<>(interceptors.size() + 1); customedInterceptors.addAll(interceptors); customedInterceptors.add(interceptor); loadBalancedRestTemplate.setInterceptors(customedInterceptors); }
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password)); SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .useTLS() .build(); SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); HttpClient httpClient = HttpClientBuilder.create() .disableRedirectHandling() .setDefaultCredentialsProvider(credentialsProvider) .setSSLSocketFactory(connectionFactory) .build(); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); restTemplate.getInterceptors().addAll(interceptors); return restTemplate; }
public TracingRestTemplateTest() { final RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList( new TracingRestTemplateInterceptor(mockTracer))); client = new Client<RestTemplate>() { @Override public <T> ResponseEntity<T> getForEntity(String url, Class<T> clazz) { return restTemplate.getForEntity(url, clazz); } @Override public RestTemplate template() { return restTemplate; } }; mockServer = MockRestServiceServer.bindTo(client.template()).build(); }
/** * Sets the api key. * * @throws JsonParseException the json parse exception * @throws JsonMappingException the json mapping exception * @throws IOException Signals that an I/O exception has occurred. */ private void setApiKey() throws JsonParseException, JsonMappingException, IOException{ ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add((HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> { if(body.length > 0) { body = addTokenInObject(body, new JsonNodeFormatter()); }else{ try { request = addTokenInURI(request); } catch (URISyntaxException e) { e.printStackTrace(); } } return execution.execute(request, body); }); this.restTemplate.setInterceptors(interceptors); }
/** * 通过urlhttp的get的请求,适合无参的场景<br> * @param restPath * @return T * @Author fanyaowu * @data 2014年7月11日 * @exception * @version * */ public static <T> T doGet(String restPath, Class<T> responseType, MediaType mediaType) throws RestInvocationException { try { ClientHttpRequestInterceptor requestInterceptor = new AcceptHeaderHttpRequestInterceptor(mediaType); restTemplate.setInterceptors(Collections.singletonList(requestInterceptor)); return restTemplate.getForObject(restPath, responseType); } catch (Exception e) { throw new RestInvocationException("Failed to request get url: " + restPath, e); } }
@Test public void testZg2Template() { Zg2proRestTemplate z0 = new Zg2proRestTemplate(); assertThat(z0.getErrorHandler()).isInstanceOf(RestTemplateErrorHandler.class); assertThat(z0.getInterceptors().size()).isGreaterThan(0); List<ClientHttpRequestInterceptor> lInterceptors = new ArrayList<>(); lInterceptors.add(new LoggingRequestInterceptor()); List<HttpMessageConverter<?>> covs = z0.getMessageConverters(); z0 = new Zg2proRestTemplate(null, lInterceptors); assertThat(z0).isNotNull(); Zg2proRestTemplate z = new Zg2proRestTemplate(covs, null); z.setInterceptors(lInterceptors); assertThat(z.getInterceptors().size()).isGreaterThan(0); z.setRequestFactory(LoggingRequestFactoryFactory.build()); assertThat(z.getInterceptors().size()).isGreaterThan(0); assertThat(z.getErrorHandler()).isInstanceOf(RestTemplateErrorHandler.class); rt.getRestTemplate().setRequestFactory(z.getRequestFactory()); ResponseEntity<String> resp; resp = rt.getForEntity(MockedControllers.TEST_URL_GET_BLANK_REPLY, String.class); assertNotNull(resp); ReturnedStructure rs = rt.getForObject(TEST_URL_GET_STRUCTURE, ReturnedStructure.class); assertThat(rs.getFieldOne()).isEqualTo(12); }
public MMLWebFeatureServiceRequestTemplate(MMLProperties mmlProperties, ClientHttpRequestFactory clientHttpRequestFactory) { this.mmlProperties = mmlProperties; this.restTemplate = new RestTemplate(clientHttpRequestFactory); final List<MediaType> xmlMediaTypes = Lists.newArrayList( MediaType.APPLICATION_XML, MediaType.TEXT_XML, new MediaType("application", "*+xml"), new MediaType("application", "vnd.ogc.se_xml")); final SourceHttpMessageConverter<Source> xmlConverter = new SourceHttpMessageConverter<>(); xmlConverter.setSupportedMediaTypes(xmlMediaTypes); final List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(xmlConverter); final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new BasicAuthenticationClientInterceptor( mmlProperties.getWfsUsername(), mmlProperties.getWfsPassword())); this.restTemplate.setMessageConverters(messageConverters); this.restTemplate.setInterceptors(interceptors); }
public void doCall() { RestTemplate restTemplate = new RestTemplate(); ClientHttpRequestInterceptor ri = new LoggingRequestInterceptor(); List<ClientHttpRequestInterceptor> ris = new ArrayList<ClientHttpRequestInterceptor>(); ris.add(ri); restTemplate.setInterceptors(ris); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("grant_type", "client_credentials"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add("Authorization", "Basic " + credentialsBuilder.getCredentialsString()); headers.add("Accept", "*/*"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); AuthResponse authToken = restTemplate.postForObject(config.getRestProperty("environment") + "/v2/auth/token", requestEntity, AuthResponse.class); tokenHolder.resetToken(authToken); }
/** * Init */ @PostConstruct protected void init() { restTemplateForAuthenticationFlow = new CookieStoreRestTemplate(); cookieStore = restTemplateForAuthenticationFlow.getCookieStore(); logger.debug("Inject cookie store used in the rest template for authentication flow into the authRestTemplate so that they will match"); authRestTemplate.restTemplate.setCookieStoreAndUpdateRequestFactory(cookieStore); List<ClientHttpRequestInterceptor> interceptors = Collections .<ClientHttpRequestInterceptor>singletonList(new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { if (latestCsrfToken != null) { // At the beginning of auth flow, there's no token yet injectCsrfTokenIntoHeader(request, latestCsrfToken); } return execution.execute(request, body); } }); restTemplateForAuthenticationFlow.setRequestFactory(new InterceptingClientHttpRequestFactory(restTemplateForAuthenticationFlow.getRequestFactory(), interceptors)); }
@Bean(name = "customerAccountServiceRestTemplate") public RestOperations getCustomerAccountServiceRestTemplate() { LOGGER.info("getCustomerAccountServiceRestTemplate()"); AccessTokenRequest atr = new DefaultAccessTokenRequest(); OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(getResourceDetails(), new DefaultOAuth2ClientContext(atr)); // Setting the interceptors to add YaaS specific http header properties List<ClientHttpRequestInterceptor> listOfInterceptors = new ArrayList<>(); listOfInterceptors.add(new YaasRequestInterceptor()); listOfInterceptors.add(new DebugClientHttpRequestInterceptor()); restTemplate.setInterceptors(listOfInterceptors); // Setting the response error handler for the rest template restTemplate.setErrorHandler(new CustomerAccountResponseErrorHandler()); return restTemplate; }
@Override protected Void doInBackground(Class<RSP>... params) { RestTemplate restTemplate = new RestTemplate(); List<ClientHttpRequestInterceptor> ris = new ArrayList<>(); ris.add(new LoggingRequestInterceptor()); ris.add(new AuthenticatingGetInterceptor()); restTemplate.setInterceptors(ris); BaseDomainResponse<RSP> result = new BaseDomainResponse<>(); try { result.setResult(restTemplate.getForObject(getRequestString(), params[0], new Object[]{})); } catch (HttpClientErrorException e) { result.setStatus(e.getStatusCode().value()); context.setFaulty(true); } block.offer((BaseDomainResponse<RS>) result); return null; }
@Override protected AuthResponse doInBackground(Void... params) { RestTemplate restTemplate = new RestTemplate(); ClientHttpRequestInterceptor ri = new LoggingRequestInterceptor(); List<ClientHttpRequestInterceptor> ris = new ArrayList<>(); ris.add(ri); restTemplate.setInterceptors(ris); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("grant_type", "client_credentials"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add("Authorization", "Basic " + credentialsBuilder.getCredentialsString()); headers.add("Accept", "*/*"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); AuthResponse authToken = restTemplate.postForObject(config.getRestProperty("environment") + "/v2/auth/token", requestEntity, AuthResponse.class); block.offer(authToken); return authToken; }
@Bean(name = "userInfoRestTemplate") public OAuth2RestTemplate userInfoRestTemplate() { if (this.details == null) { this.details = DEFAULT_RESOURCE_DETAILS; } OAuth2RestTemplate template = getTemplate(); template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList( new AcceptJsonRequestInterceptor())); AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider(); accessTokenProvider.setTokenRequestEnhancer(new AcceptJsonRequestEnhancer()); template.setAccessTokenProvider(accessTokenProvider); AnnotationAwareOrderComparator.sort(this.customizers); for (UserInfoRestTemplateCustomizer customizer : this.customizers) { customizer.customize(template); } return template; }
@Bean public InitializingBean clientsCorrelationInitializer(final RequestCorrelationProperties properties) { return new InitializingBean() { @Override public void afterPropertiesSet() throws Exception { if(clients != null) { for(InterceptingHttpAccessor client : clients) { final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(client.getInterceptors()); interceptors.add(new ClientHttpRequestCorrelationInterceptor(properties)); client.setInterceptors(interceptors); } } } }; }
@Override public RestExecutor createRestExecutor() { RestExecutorConfig config = this.restExecutorConfig; if(config==null){ config = new RestExecutorConfig(); } ExtRestTemplate restTemplate = null; if(RestUtils.isOkHttp3Present()){ OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory(); requestFactory.setConnectTimeout(config.getConnectTimeout()); requestFactory.setReadTimeout(config.getReadTimeout()); requestFactory.setWriteTimeout(config.getWriteTimeout()); restTemplate = new ExtRestTemplate(requestFactory); }else{ restTemplate = new ExtRestTemplate(); } if(restExecutorInterceptors!=null){ List<ClientHttpRequestInterceptor> interList = restTemplate.getInterceptors(); if(interList==null){ interList = Lists.newArrayList(); restTemplate.setInterceptors(interList); } // interList.addAll(restExecutorRequestInterceptors); } return restTemplate; }
/** {@inheritDoc} */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) { // RestTemplate et getInterceptors() existent depuis spring-web 3.1.0.RELEASE if (REST_TEMPLATE_INTERCEPTOR_AVAILABLE && bean instanceof RestTemplate) { final RestTemplate restTemplate = (RestTemplate) bean; final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>( restTemplate.getInterceptors()); for (final ClientHttpRequestInterceptor interceptor : interceptors) { if (interceptor instanceof SpringRestTemplateInterceptor) { return bean; } } interceptors.add(SpringRestTemplateInterceptor.SINGLETON); restTemplate.setInterceptors(interceptors); } return bean; }
@PostConstruct public void init() { jsonMapper.enable(SerializationFeature.WRAP_ROOT_VALUE); template.getInterceptors().add(new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().add("Accept", "application/json"); request.getHeaders().add("Content-Type", "application/json"); request.getHeaders().add("User-Agent", ""); return execution.execute(request, body); } }); //paymentContext = new PaymillContext(secret); }
/** * Add any interceptors found in the application context, e.g. for logging, which may or may not be present * based on profiles. */ @Autowired(required = false) @Override public void setInterceptors(List<ClientHttpRequestInterceptor> interceptors) { if (interceptors.isEmpty()) { logger.info("No HTTP request interceptors have been found in the application context."); return; } for (ClientHttpRequestInterceptor interceptor : interceptors) { logger.info("The interceptor '{}' will be added to this provider.", interceptor.getClass().getSimpleName()); } super.setInterceptors(interceptors); }
@Test @OAuth2ContextConfiguration(resource = AutoApproveImplicit.class, initialize = false) public void testPostForAutomaticApprovalToken() throws Exception { final ImplicitAccessTokenProvider implicitProvider = new ImplicitAccessTokenProvider(); implicitProvider.setInterceptors(Arrays .<ClientHttpRequestInterceptor> asList(new ClientHttpRequestInterceptor() { public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ClientHttpResponse result = execution.execute(request, body); latestHeaders = result.getHeaders(); return result; } })); context.setAccessTokenProvider(implicitProvider); context.getAccessTokenRequest().setCookie(cookie); assertNotNull(context.getAccessToken()); assertTrue("Wrong location header: " + latestHeaders.getLocation().getFragment(), latestHeaders.getLocation().getFragment() .contains("scope=read write trust")); }
@Before public void initRestTemplate() { // 默认使用JDK Connection jdkTemplate = new RestTemplate(); // (optional)设置20秒超时 ((SimpleClientHttpRequestFactory) jdkTemplate.getRequestFactory()).setConnectTimeout(20000); // 设置使用HttpClient4.0 httpClientRestTemplate = new RestTemplate(); httpClientRequestFactory = new HttpComponentsClientHttpRequestFactory(); // (optional)设置20秒超时 httpClientRequestFactory.setConnectTimeout(20000); httpClientRestTemplate.setRequestFactory(httpClientRequestFactory); // 设置处理HttpBasic Header的Interceptor ClientHttpRequestInterceptor interceptor = new HttpBasicInterceptor("admin", "admin"); httpClientRestTemplate.setInterceptors(Lists.newArrayList(interceptor)); }
@Override public RestTemplate createRestTemplate() { RestTemplate restTemplate = new RestTemplate(); // web services support json responses GsonHttpMessageConverter jsonConverter = new GsonHttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.TEXT_HTML); jsonConverter.setSupportedMediaTypes(mediaTypes); final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters(); listHttpMessageConverters.add(jsonConverter); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new AcceptHeaderHttpClientInterceptor()); restTemplate.setInterceptors(interceptors); restTemplate.setMessageConverters(listHttpMessageConverters); return restTemplate; }
public static RestTemplate getTemplate(ClientHttpRequestInterceptor interceptor) { RestTemplate restTemplate = new RestTemplate(); List<ClientHttpRequestInterceptor> ris = new ArrayList<>(); ris.add(interceptor); restTemplate.setInterceptors(ris); SimpleClientHttpRequestFactory httpFactory = new SimpleClientHttpRequestFactory(); httpFactory.setOutputStreaming(false); restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(httpFactory)); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); return restTemplate; }
@Test public void setInterceptorsWithUnderlying() { ClientHttpRequestInterceptor interceptor1 = mock(ClientHttpRequestInterceptor.class); ClientHttpRequestInterceptor interceptor2 = mock(ClientHttpRequestInterceptor.class); List<ClientHttpRequestInterceptor> interceptors = asList(interceptor1, interceptor2); wrapper.setInterceptors(interceptors); assertThat(wrapper.getInterceptors(), contains(interceptor1, interceptor2)); assertThat(wrapper.defaultRestTemplate.getInterceptors(), contains(interceptor1, interceptor2)); verify(underlying, never()).setInterceptors(interceptors); }
@Bean public RestTemplate restTemplate(OmegaContext context) { RestTemplate template = new RestTemplate(); List<ClientHttpRequestInterceptor> interceptors = template.getInterceptors(); interceptors.add(new TransactionClientHttpRequestInterceptor(context)); template.setInterceptors(interceptors); return template; }
@Test public void testErrorUnknownHostException() { String url = "http://nonexisting.example.com"; try { RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList( new TracingRestTemplateInterceptor(mockTracer))); restTemplate.getForEntity(url, String.class); } catch (ResourceAccessException ex) { //ok UnknownHostException } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(RestTemplateSpanDecorator.StandardTags.COMPONENT_NAME, mockSpan.tags().get(Tags.COMPONENT.getKey())); Assert.assertEquals(Tags.SPAN_KIND_CLIENT, mockSpan.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(url, mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(1, mockSpan.logEntries().size()); Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size()); Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event")); Assert.assertNotNull(mockSpan.logEntries().get(0).fields().get("error.object")); }
private void registerTracingInterceptor(RestTemplate restTemplate) { List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); for (ClientHttpRequestInterceptor interceptor: interceptors) { if (interceptor instanceof TracingRestTemplateInterceptor) { return; } } log.info("Adding " + TracingRestTemplateInterceptor.class.getSimpleName() + " to rest template"); interceptors = new ArrayList<>(interceptors); interceptors.add(new TracingRestTemplateInterceptor(tracer)); restTemplate.setInterceptors(interceptors); }
@Override public void customize(RestTemplate restTemplate) { UriTemplateHandler templateHandler = restTemplate.getUriTemplateHandler(); templateHandler = this.interceptor.createUriTemplateHandler(templateHandler); restTemplate.setUriTemplateHandler(templateHandler); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(this.interceptor); interceptors.addAll(restTemplate.getInterceptors()); restTemplate.setInterceptors(interceptors); }
/** * Gets a Rest Template. * * @return A RestTemplate for rest requests. */ public RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); // Request Interceptors restTemplate.setInterceptors(new ArrayList<ClientHttpRequestInterceptor>()); restTemplate.getInterceptors().addAll(getRestInterceptors()); // Default Error Handler restTemplate.setErrorHandler(new RestErrorHandler()); return restTemplate; }
@Bean @Override public RestTemplateBuilder restTemplateBuilder() { final ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException { if (logger.isInfoEnabled()) { logger.info(new String(body)); } return execution.execute(request, body); } }; return super.restTemplateBuilder().additionalInterceptors(interceptor); }
private void addAuthentication() { if (StringUtils.isEmpty(username)) { throw new RuntimeException("Username is mandatory for Basic Auth"); } List<ClientHttpRequestInterceptor> interceptors = Collections .singletonList(new BasicAuthInterceptor(username, password)); setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(), interceptors)); }
private RestOperations createRestOperations(String username, String password) { RestTemplate restTemplate = new RestTemplate(); ClientHttpRequestInterceptor basicAuthInterceptor = new BasicAuthorizationInterceptor(username, password); restTemplate.getInterceptors().add(basicAuthInterceptor); return restTemplate; }
public RestTemplate GetClient() { if (proxyEnabled) { proxyEnabled = false; ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setProxy(new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))); } if (restTemplate.getInterceptors().size() == 0 || restTemplate.getInterceptors().size() == 1) { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new HttpHeaderInterceptor(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)); if (null != requestCallContext.GetUser()) { interceptors.add(new HttpHeaderInterceptor(HttpHeaders.COOKIE, CookieCache.Get(requestCallContext.GetUser()))); } restTemplate.setInterceptors(interceptors); } return restTemplate; }
public static List<ClientHttpRequestInterceptor> getRequestInterceptors(){ RewritePropertiesRequestInterceptor rewriterRequest = new RewritePropertiesRequestInterceptor(); LoggingRequestInterceptor loggingRequestInterceptor = new LoggingRequestInterceptor(); List<ClientHttpRequestInterceptor> ris = new ArrayList<ClientHttpRequestInterceptor>(); ris.add(loggingRequestInterceptor); ris.add(rewriterRequest); return ris; }
private static LoggingRequestFactory interceptorToRequestFactory(LoggingRequestInterceptor lri) { List<ClientHttpRequestInterceptor> lInterceptors = new ArrayList<>(); lInterceptors.add(lri); SimpleClientHttpRequestFactory chrf = new SimpleClientHttpRequestFactory(); chrf.setOutputStreaming(false); return new LoggingRequestFactory( new BufferingClientHttpRequestFactory(chrf), lInterceptors ); }
protected AbstractZg2proRestTemplate(@Nullable List<HttpMessageConverter<?>> lConverters, @Nullable List<ClientHttpRequestInterceptor> lInterceptors) { super(); this.setErrorHandler(new RestTemplateErrorHandler()); if (!CollectionUtils.isEmpty(lConverters)) { //emptiness is rechecked inside setMessageConverters but it may change //in a future spring release setMessageConverters(lConverters); } if (lInterceptors == null) { lInterceptors = new ArrayList<>(); } }
@Override protected void interceptorsIntegration(List<ClientHttpRequestInterceptor> lInterceptors, Object sslConfiguration) { this.setInterceptors(lInterceptors); SimpleClientHttpRequestFactory chrf = new SimpleClientHttpRequestFactory(); chrf.setOutputStreaming(false); this.setRequestFactory( new InterceptingClientHttpRequestFactory( new BufferingClientHttpRequestFactory(chrf), lInterceptors ) ); }
/** * hard to check the logs provided by the interceptor when there's no error * however this unit test garantees the interceptor does not alter the reply * from the rest service. */ @Test public void testInterceptor() { List<ClientHttpRequestInterceptor> lInterceptors = new ArrayList<>(); //spring boot default log level is info lInterceptors.add(new LoggingRequestInterceptor(StandardCharsets.ISO_8859_1, 100, Level.ERROR)); SimpleClientHttpRequestFactory chrf = new SimpleClientHttpRequestFactory(); chrf.setOutputStreaming(false); rt.getRestTemplate().setRequestFactory(new InterceptingClientHttpRequestFactory( new BufferingClientHttpRequestFactory(chrf), lInterceptors )); ResponseEntity<String> resp = rt.getForEntity(MockedControllers.TEST_URL_GET, String.class); assertThat(resp.getBody()).isEqualTo(MockedControllers.TEST_RETURN_VALUE); }
@Bean public UserInfoRestTemplateCustomizer userInfoRestTemplateCustomizer( TraceRestTemplateInterceptor traceRestTemplateInterceptor) { return restTemplate -> { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>( restTemplate.getInterceptors()); interceptors.add(traceRestTemplateInterceptor); restTemplate.setInterceptors(interceptors); }; }