当前位置: 首页>>代码示例>>Java>>正文


Java RestTemplate.setRequestFactory方法代码示例

本文整理汇总了Java中org.springframework.web.client.RestTemplate.setRequestFactory方法的典型用法代码示例。如果您正苦于以下问题:Java RestTemplate.setRequestFactory方法的具体用法?Java RestTemplate.setRequestFactory怎么用?Java RestTemplate.setRequestFactory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.web.client.RestTemplate的用法示例。


在下文中一共展示了RestTemplate.setRequestFactory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
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;
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:13,代码来源:TemplateUtil.java

示例2: afterPropertiesSet

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public void afterPropertiesSet() throws UnsupportedEncodingException {
  Collection<Header> defaultHeaders = new ArrayList<Header>();
  Header header = new BasicHeader("Authorization",
      "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8")));
  defaultHeaders.add(header);

  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY,
      new UsernamePasswordCredentials("apollo", ""));
  CloseableHttpClient httpClient =
      HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
          .setDefaultHeaders(defaultHeaders).build();


  restTemplate = new RestTemplate(httpMessageConverters.getConverters());
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(httpClient);
  requestFactory.setConnectTimeout(portalConfig.connectTimeout());
  requestFactory.setReadTimeout(portalConfig.readTimeout());

  restTemplate.setRequestFactory(requestFactory);
}
 
开发者ID:dewey-its,项目名称:apollo-custom,代码行数:23,代码来源:RestTemplateFactory.java

示例3: disableSSL

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static void disableSSL(RestTemplate restTemplate) {
    try {
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true)
            .build();
        CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
            .build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(requestFactory));
    } catch (Exception e) {
        log.error("Exception occurred while creating http factory, error={}", e.getMessage(), e);
    }
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:16,代码来源:TemplateUtil.java

示例4: buildRestTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Build the RestTemplate used to make HTTP requests.
 * @return RestTemplate
 */
protected RestTemplate buildRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    // This allows us to read the response more than once - Necessary for debugging.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    return restTemplate;
}
 
开发者ID:jopache,项目名称:Settings,代码行数:11,代码来源:ApiClient.java

示例5: createRestTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean
        trustSelfSignedCerts) {
    RestTemplate restTemplate = new LoggingRestTemplate();
    restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts));
    restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler());
    restTemplate.setMessageConverters(getHttpMessageConverters());

    return restTemplate;
}
 
开发者ID:SAP,项目名称:cf-java-client-sap,代码行数:10,代码来源:RestUtil.java

示例6: assertNetworkCallFails

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private void assertNetworkCallFails(RestTemplate restTemplate, ClientHttpRequestFactory requestFactory) {
    restTemplate.setRequestFactory(requestFactory);
    try {
        HttpStatus status = restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, new ResponseExtractor<HttpStatus>() {
            public HttpStatus extractData(ClientHttpResponse response) throws IOException {
                return response.getStatusCode();
            }
        });
        Assert.fail("Expected byteman rules to detect direct socket connections, status is:" + status);
    } catch (Exception e) {
        // good, byteman rejected it as expected
        // e.printStackTrace();
    }
    assertEquals("Not expecting Jetty to receive requests since we asked direct connections", 0, nbInJvmProxyRcvReqs.get());
}
 
开发者ID:SAP,项目名称:cf-java-client-sap,代码行数:16,代码来源:CloudFoundryClientTest.java

示例7: setUp

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Before
public void setUp()
{
	Log log = mock(Log.class);
	when(log.isDebugEnabled()).thenReturn(true);
	loggingCustomizer = new LoggingCustomizer(log);
	
	restTemplate = new RestTemplate();
	restTemplate.setRequestFactory(requestFactory);
}
 
开发者ID:markhobson,项目名称:spring-rest-template-logger,代码行数:11,代码来源:LoggingCustomizerTest.java

示例8: update

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Async
public void update(final String keycloakToken) {
    RestTemplate template = new KeycloakRestTemplate(keycloakToken);
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    template.setRequestFactory(requestFactory);
    ResponseEntity<String> response = template.exchange(updateTenantEndpoint, HttpMethod.PATCH, null, String.class);
    LOG.info("User tenant has been updated. Status code {}", response.getStatusCode());
}
 
开发者ID:redhat-developer,项目名称:che-starter,代码行数:9,代码来源:TenantUpdater.java

示例9: checkIfServerAlreadyRunning

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Checks if the data server is already running, by calling the /health endpoint.
 * @return <code>true</code> if running
 */
private static boolean checkIfServerAlreadyRunning() {
    logger.info("In DataServerManager.checkIfServerAlreadyRunning");

    try {
        // issue a GET to Spring Boot health endpoint to determine if data server is already running...
        // (it returns a short JSON reply message)
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(500); // set short connect timeout
        requestFactory.setReadTimeout(2000); // set slightly longer read timeout
        restTemplate.setRequestFactory(requestFactory);
        String result = restTemplate.getForObject("http://localhost:9999/health", String.class);
        logger.info("Server is already running, received {}", result);
        return true;

    } catch (RestClientException ex) {
        logger.info("Server not already running");
        return false;
    }
}
 
开发者ID:dvsa,项目名称:mot-automated-testsuite,代码行数:25,代码来源:DataServerManager.java

示例10: initRestTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * springboot初始化restTemplate
 */
@Bean
public RestTemplate initRestTemplate() {
    // 长连接保持30秒
    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
    // 总连接数
    pollingConnectionManager.setMaxTotal(1000);
    // 同路由的并发数
    pollingConnectionManager.setDefaultMaxPerRoute(1000);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // 重试次数,默认是3次,没有开启
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // 保持长连接配置,需要在头添加Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectionRequestTimeout(200);
    builder.setConnectTimeout(5000);
    builder.setSocketTimeout(5000);

    RequestConfig requestConfig = builder.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));

    httpClientBuilder.setDefaultHeaders(headers);

    HttpClient httpClient = httpClientBuilder.build();

    // httpClient连接配置,底层是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 连接超时
    clientHttpRequestFactory.setConnectTimeout(5000);
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(5000);
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(200);
    // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
    clientHttpRequestFactory.setBufferRequestBody(false);

    // 添加内容转换器
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(initStringHttpMessageConverter());
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    restTemplate.setRequestFactory(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
    return restTemplate;

}
 
开发者ID:wu05281,项目名称:admin-shiro,代码行数:62,代码来源:RestTemplateConfig.java

示例11: getRawRestTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private RestTemplate getRawRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();

    restTemplate.getMessageConverters().add(
            new ByteArrayHttpMessageConverter());

    restTemplate.setRequestFactory(
            new InterceptingClientHttpRequestFactory(
                    restTemplate.getRequestFactory(),
                    Collections.singletonList(
                            new BasicAuthorizationInterceptor("1", "1"))));
    return restTemplate;
}
 
开发者ID:JUGIstanbul,项目名称:second-opinion-api,代码行数:14,代码来源:MediaDownloadControllerIT.java

示例12: prepareRestTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(
		RestTemplate restTemplate,
		String username,
		String password,
		boolean skipSslValidation) {

	Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

	final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

	if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
		final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY,
				new UsernamePasswordCredentials(
						username,
						password));
		httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
	}

	if (skipSslValidation) {
		httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
		httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
	}

	final CloseableHttpClient httpClient = httpClientBuilder.build();
	final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
	restTemplate.setRequestFactory(requestFactory);
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-dashboard,代码行数:41,代码来源:HttpClientUtils.java

示例13: configureRestTemplate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Configure a {@link RestTemplate} for communication with a CredHub server.
 * @param restTemplate an existing {@link RestTemplate} to configure
 * @param baseUri the base URI for the CredHub server
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 */
public static void configureRestTemplate(RestTemplate restTemplate, String baseUri,
		ClientHttpRequestFactory clientHttpRequestFactory) {
	restTemplate.setRequestFactory(clientHttpRequestFactory);
	restTemplate.setUriTemplateHandler(createUriTemplateHandler(baseUri));
	restTemplate.setMessageConverters(createMessageConverters());
	restTemplate.setInterceptors(createInterceptors());
}
 
开发者ID:spring-projects,项目名称:spring-credhub,代码行数:15,代码来源:CredHubClient.java

示例14: configureCloudFoundryRequestFactory

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
protected void configureCloudFoundryRequestFactory(RestTemplate restTemplate) {
    ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
    if (!(requestFactory instanceof CloudFoundryClientHttpRequestFactory)) {
        restTemplate.setRequestFactory(new CloudFoundryClientHttpRequestFactory(requestFactory));
    }
}
 
开发者ID:SAP,项目名称:cf-java-client-sap,代码行数:7,代码来源:CloudControllerClientImpl.java

示例15: customize

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Override
public void customize(RestTemplate restTemplate)
{
	restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
	restTemplate.getInterceptors().add(new LoggingInterceptor(log));
}
 
开发者ID:markhobson,项目名称:spring-rest-template-logger,代码行数:7,代码来源:LoggingCustomizer.java


注:本文中的org.springframework.web.client.RestTemplate.setRequestFactory方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。