Java Code Examples for org.springframework.web.client.RestTemplate#setInterceptors()
The following examples show how to use
org.springframework.web.client.RestTemplate#setInterceptors() .
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: RestTemplateCircuitBreakerAutoConfiguration.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
@Bean public SmartInitializingSingleton loadBalancedRestTemplateInitializer2( final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) { return () -> { logger.info("RestTemplateResilienceAutoConfiguration init2"); for (RestTemplate restTemplate : RestTemplateCircuitBreakerAutoConfiguration.this.restTemplates) { List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); logger.info("RestTemplate init2 start,interceptor size:" + interceptors.size()); //for (ClientHttpRequestInterceptor interceptor : interceptors) { //logger.info("RestTemplate init2 interceptor ing:"+interceptor.getClass().getCanonicalName()); //} //logger.info("RestTemplate init2 Customizer end"); ClientHttpRequestInterceptor interceptor1 = new RestTemplateCircuitBreakerInterceptor (circuitBreakerCore); interceptors.add(0, interceptor1); restTemplate.setInterceptors(interceptors); logger.info("RestTemplate init2 end,add CircuitBreaker interceptor"); } }; }
Example 2
Source File: MultiModuleConfigServicePropertySourceLocator.java From spring-cloud-formula with Apache License 2.0 | 6 votes |
private RestTemplate getSecureRestTemplate(ConfigClientProperties properties) { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); if (properties.getRequestReadTimeout() < 0) { throw new IllegalStateException("Invalid Value for Real Timeout set."); } requestFactory.setReadTimeout(properties.getRequestReadTimeout()); RestTemplate template = new RestTemplate(requestFactory); Map<String, String> headers = new HashMap<>(properties.getHeaders()); headers.remove(AUTHORIZATION); // To avoid redundant addition of header if (!headers.isEmpty()) { template.setInterceptors(Collections.singletonList(new GenericRequestHeaderInterceptor(headers))); } return template; }
Example 3
Source File: ScmPropertySourceLocator.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * Create rest template. * * @param readTimeout * @return */ public RestTemplate createRestTemplate(long readTimeout) { Assert.state(readTimeout > 0, String.format("Invalid value for read timeout for %s", readTimeout)); Netty4ClientHttpRequestFactory factory = new Netty4ClientHttpRequestFactory(); factory.setConnectTimeout(config.getConnectTimeout()); factory.setReadTimeout((int) readTimeout); factory.setMaxResponseSize(config.getMaxResponseSize()); RestTemplate restTemplate = new RestTemplate(factory); Map<String, String> headers = new HashMap<>(config.getHeaders()); if (headers.containsKey(AUTHORIZATION)) { // To avoid redundant addition of header headers.remove(AUTHORIZATION); } if (!headers.isEmpty()) { restTemplate.setInterceptors(asList(new GenericRequestHeaderInterceptor(headers))); } return restTemplate; }
Example 4
Source File: RestTemplateInitializingBean.java From summerframework with Apache License 2.0 | 6 votes |
@Override public void afterPropertiesSet() throws Exception { if (null != restTemplateList) { for (RestTemplate restTemplate : restTemplateList) { List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); if (interceptors == null) { restTemplate.setInterceptors(Arrays.asList(grayClientHttpRequestInterceptor)); } else { List<ClientHttpRequestInterceptor> newInterceptors = new ArrayList<>(); newInterceptors.addAll(interceptors); newInterceptors.add(grayClientHttpRequestInterceptor); restTemplate.setInterceptors(newInterceptors); } } } }
Example 5
Source File: AllureRestTemplateTest.java From allure-java with Apache License 2.0 | 6 votes |
protected final AllureResults execute() { final RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); restTemplate.setInterceptors(Collections.singletonList(new AllureRestTemplate())); final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort()); return runWithinTestContext(() -> { server.start(); WireMock.configureFor(server.port()); WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/hello")).willReturn(WireMock.aResponse().withBody("some body"))); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<JsonNode> entity = new HttpEntity<>(headers); ResponseEntity<String> result = restTemplate.exchange(server.url("/hello"), HttpMethod.GET, entity, String.class); Assertions.assertEquals(result.getStatusCode(), HttpStatus.OK); } finally { server.stop(); } }); }
Example 6
Source File: SpringRestTemplateBeanPostProcessor.java From javamelody with Apache License 2.0 | 6 votes |
/** {@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); LOG.debug("rest template interceptor initialized"); } return bean; }
Example 7
Source File: LicensingserviceApplication.java From demo-project with MIT License | 5 votes |
/** * 使用带有Ribbon 功能的Spring RestTemplate */ @LoadBalanced @Bean @SuppressWarnings("unchecked") public RestTemplate getRestTemplate(){ RestTemplate restTemplate = new RestTemplate(); //加上拦截器,发出请求前加入管理id Header List interceptors = restTemplate.getInterceptors(); if(interceptors==null){ restTemplate.setInterceptors(Collections.singletonList(new UserContextInterceptor())); }else{ interceptors.add(new UserContextInterceptor()); } return restTemplate; }
Example 8
Source File: CloudFoundryClientFactory.java From multiapps-controller with Apache License 2.0 | 5 votes |
private void addTaggingInterceptor(RestTemplate template, String org, String space) { if (template.getInterceptors() .isEmpty()) { template.setInterceptors(new ArrayList<>()); } ClientHttpRequestInterceptor requestInterceptor = new TaggingRequestInterceptor(configuration.getVersion(), org, space); template.getInterceptors() .add(requestInterceptor); }
Example 9
Source File: RestTemplateConfig.java From txle with Apache License 2.0 | 5 votes |
@Bean public RestTemplate restTemplate(@Autowired(required = false) OmegaContext context, @Autowired Tracing tracing) { RestTemplate template = new RestTemplate(); List<ClientHttpRequestInterceptor> interceptors = template.getInterceptors(); interceptors.add(new TransactionClientHttpRequestInterceptor(context)); // add interceptor for rest's request server By Gannalyo interceptors.add(TracingClientHttpRequestInterceptor.create(tracing)); template.setInterceptors(interceptors); return template; }
Example 10
Source File: TraceWebClientAutoConfiguration.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
void inject(RestTemplate restTemplate) { if (hasTraceInterceptor(restTemplate)) { return; } List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>( restTemplate.getInterceptors()); interceptors.add(0, this.interceptor); restTemplate.setInterceptors(interceptors); }
Example 11
Source File: UaaConnectionHelper.java From uaa-java-client with Apache License 2.0 | 5 votes |
/** * Make a REST call with custom headers * * @param method the Http Method (GET, POST, etc) * @param uri the URI of the endpoint (relative to the base URL set in the constructor) * @param body the request body * @param responseType the object type to be returned * @param uriVariables any uri variables * @return the response body * @see org.springframework.web.client.RestTemplate#exchange(String, HttpMethod, HttpEntity, ParameterizedTypeReference, Object...) */ private <RequestType, ResponseType> ResponseType exchange(HttpMethod method, HttpHeaders headers, RequestType body, String uri, ParameterizedTypeReference<ResponseType> responseType, Object... uriVariables) { getHeaders(headers); RestTemplate template = new RestTemplate(); template.setInterceptors(LoggerInterceptor.INTERCEPTOR); HttpEntity<RequestType> requestEntity = null; if (body == null) { requestEntity = new HttpEntity<RequestType>(headers); } else { requestEntity = new HttpEntity<RequestType>(body, headers); } // combine url into the varargs List<Object> varList = new ArrayList<Object>(); varList.add(url); if (uriVariables != null && uriVariables.length > 0) { varList.addAll(Arrays.asList(uriVariables)); } ResponseEntity<ResponseType> responseEntity = template.exchange("{base}" + uri, method, requestEntity, responseType, varList.toArray()); if (HttpStatus.Series.SUCCESSFUL.equals(responseEntity.getStatusCode().series())) { return responseEntity.getBody(); } else { return null; } }
Example 12
Source File: WebSocketDocsTest.java From chassis with Apache License 2.0 | 5 votes |
@Test public void testProtobufMessagesSchema() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "false"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); ResponseEntity<String> response = httpClient.getForEntity( new URI("http://localhost:" + properties.get("admin.port") + "/schema/messages/protobuf"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().contains("message error")); } finally { context.close(); } }
Example 13
Source File: MicroWebConfig.java From sample-boot-micro with MIT License | 5 votes |
/** * Ribbon 経由で Eureka がサポートしているサービスを実行するための RestTemplate。 * <p>リクエスト時に利用者情報を紐づけています。 */ @Bean @LoadBalanced RestTemplate restTemplate(ActorSession session) { RestTemplate tmpl = new RestTemplate(); tmpl.setInterceptors(new ArrayList<>(Arrays.asList( new RestActorSessionInterceptor(session) ))); return tmpl; }
Example 14
Source File: SofaTracerRestTemplateEnhance.java From sofa-tracer with Apache License 2.0 | 5 votes |
public void enhanceRestTemplateWithSofaTracer(RestTemplate restTemplate) { // check interceptor if (checkRestTemplateInterceptor(restTemplate)) { return; } List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>( restTemplate.getInterceptors()); interceptors.add(0, this.restTemplateInterceptor); restTemplate.setInterceptors(interceptors); }
Example 15
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testHealthcheck() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/healthcheck"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertEquals("OK", response.getBody()); } finally { context.close(); } }
Example 16
Source File: ITTracingClientHttpRequestInterceptor.java From brave with Apache License 2.0 | 4 votes |
@Override protected void post(ClientHttpRequestFactory client, String uri, String content) { RestTemplate restTemplate = new RestTemplate(client); restTemplate.setInterceptors(Collections.singletonList(interceptor)); restTemplate.postForObject(url(uri), content, String.class); }
Example 17
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testClassPath() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/admin/classpath"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().length() > 0); } finally { context.close(); } }
Example 18
Source File: ITTracingClientHttpRequestInterceptor.java From brave with Apache License 2.0 | 4 votes |
@Override protected void options(ClientHttpRequestFactory client, String path) { RestTemplate restTemplate = new RestTemplate(client); restTemplate.setInterceptors(Collections.singletonList(interceptor)); restTemplate.optionsForAllow(url(path), String.class); }
Example 19
Source File: SharedTest.java From chassis with Apache License 2.0 | 4 votes |
@Test public void testSwagger() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("admin.enabled", "true"); properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("admin.hostname", "localhost"); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "true"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(MetricsConfiguration.class); RestTemplate httpClient = new RestTemplate(); try { context.refresh(); httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR)); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) { messageConverters.add(new SerDeHttpMessageConverter(messageSerDe)); } messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); httpClient.setMessageConverters(messageConverters); ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/swagger/index.html"), String.class); logger.info("Got response: [{}]", response); Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value()); Assert.assertTrue(response.getBody().contains("<title>Swagger UI</title>")); } finally { context.close(); } }
Example 20
Source File: RestTemplatePostProcessor.java From log-trace-spring-boot with Apache License 2.0 | 4 votes |
private void processing(RestTemplate restTemplate) { List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); interceptors.add(new TraceClientHttpRequestInterceptor(traceContentFactory)); restTemplate.setInterceptors(interceptors); }