當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。