Java 类org.springframework.http.client.SimpleClientHttpRequestFactory 实例源码

项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:EmbeddedServletContainerMvcIntegrationTests.java   
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();
    }
}
项目:Robusto    文件:SpringRestClient.java   
/**
 * Extension point for plugging in different HTTP factories.
 * @return Default is a {@link BufferingClientHttpRequestFactory}
 */
protected ClientHttpRequestFactory createHttpFactory(
      int connectTimeout,
      int requestTimeout)
{
   SimpleClientHttpRequestFactory scrf = new SimpleClientHttpRequestFactory();
   scrf.setConnectTimeout(connectTimeout);
   scrf.setReadTimeout(requestTimeout);

   //
   // Wrap the default request factory in a BufferingClientHttpRequestFactory
   // which allows us to read response bodies multiple times. This is needed
   // because some interceptors will need to consume the body before the final
   // response gets to the caller.
   //

   return new BufferingClientHttpRequestFactory(scrf);
}
项目:spring-boot-concourse    文件:EmbeddedServletContainerMvcIntegrationTests.java   
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();
    }
}
项目:orders    文件:RestProxyTemplate.java   
@PostConstruct
public void init() {
    if (host.isEmpty() || port.isEmpty()) {
        return;
    }
    int portNr = -1;
    try {
        portNr = Integer.parseInt(port);
    } catch (NumberFormatException e) {
        logger.error("Unable to parse the proxy port number");
    }
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    InetSocketAddress address = new InetSocketAddress(host, portNr);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
    factory.setProxy(proxy);

    restTemplate.setRequestFactory(factory);
}
项目:riptide    文件:RequestUriTest.java   
@Override
public void execute(final String baseUrl, final UrlResolution resolution, final String uri,
        final HttpMethod method, final Consumer<Http> tester) {

    try {
        final Http unit = Http.builder()
                .baseUrl(baseUrl)
                .urlResolution(resolution)
                .requestFactory(new SimpleClientHttpRequestFactory())
                .build();

        tester.accept(unit);
        fail("Expected exception");
    } catch (final Exception e) {
        assertThat(e, is(instanceOf(IllegalArgumentException.class)));
        assertThat(e.getMessage(), is(message));
    }
}
项目:contestparser    文件:EmbeddedServletContainerMvcIntegrationTests.java   
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();
    }
}
项目:spring-boot-etcd    文件:EtcdClientAutoConfiguration.java   
@Bean
public EtcdClient etcdClient() throws NamingException {
    List<String> locations = discoverNodes("_etcd-server._tcp." + properties.getServiceName());

    EtcdClient client = new EtcdClient(locations.get(0));

    client.setRetryCount(properties.getRetryCount());
    client.setRetryDuration(properties.getRetryDuration());
    client.setLocationUpdaterEnabled(properties.isUpdateLocations());

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setConnectTimeout(properties.getConnectTimeout());
    requestFactory.setReadTimeout(properties.getReadTimeout());
    client.setRequestFactory(requestFactory);

    return client;
}
项目:Profiles-Blog    文件:PayloadSender.java   
@PostConstruct
public void initialize() {
    restTemplate = new RestTemplate();

    // Loose JSON serialization defaults
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
    restTemplate.setMessageConverters(Arrays.asList(converter));

    // Timeout settings
    SimpleClientHttpRequestFactory requestFactory = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
    int tenSeconds = 10000;
    requestFactory.setReadTimeout(tenSeconds);
    requestFactory.setConnectTimeout(tenSeconds);
}
项目:elpaaso-core    文件:PaasServicesEnvITHelper.java   
public <T> T executeRestRequest(LinkDto link, String path, Class<T> clazz) {

        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        if (this.getItConfiguration().isUseHttpIgeProxy()) {
            final String httpProxyHost = this.getItConfiguration().getHttpProxyHost();
            final int httpProxyPort = this.getItConfiguration().getHttpProxyPort();
            logger.info("Use proxy {}:{} to access Simple Probe", httpProxyHost, httpProxyPort);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));

            clientHttpRequestFactory.setProxy(proxy);
        }
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        T result = restTemplate.getForEntity(link.getUrl().toString()+path, clazz).getBody();

        return result;
    }
项目:elpaaso-core    文件:PaasServicesEnvSimpleProbeIT.java   
private String getRestTemplateForProbeFrom(LinkDto link,String path) {

        logger.info("Querying endpoint: {}",link.getUrl().toString()+path);
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        if (paasServicesEnvITHelper.getItConfiguration().isUseHttpIgeProxy()) {
            final String httpProxyHost = paasServicesEnvITHelper.getItConfiguration().getHttpProxyHost();
            final int httpProxyPort = paasServicesEnvITHelper.getItConfiguration().getHttpProxyPort();
            logger.info("Use proxy {}:{} to access Simple Probe", httpProxyHost, httpProxyPort);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));

            clientHttpRequestFactory.setProxy(proxy);
        }
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        HttpHeaders customHeaders = new HttpHeaders();
        customHeaders.add(HEADER_ELPAASO_UNIVERSAL_ID, HEADER_ELPAASO_UNIVERSAL_ID_DEFAULT_VALUE);

        HttpEntity<String> entity = new HttpEntity<>("parameters", customHeaders);
        ResponseEntity<String> response = restTemplate.exchange(link.getUrl().toString()+path,
                HttpMethod.GET,
                entity,
                String.class);
        String result = response.getBody();

        return result;
    }
项目:Robusto    文件:SpringRestClient.java   
/**
 * Extension point for plugging in different HTTP factories.
 * @return Default is a {@link BufferingClientHttpRequestFactory}
 */
protected ClientHttpRequestFactory createHttpFactory(
      int connectTimeout,
      int requestTimeout)
{
   SimpleClientHttpRequestFactory scrf = new SimpleClientHttpRequestFactory();
   scrf.setConnectTimeout(connectTimeout);
   scrf.setReadTimeout(requestTimeout);

   //
   // Wrap the default request factory in a BufferingClientHttpRequestFactory
   // which allows us to read response bodies multiple times. This is needed
   // because some interceptors will need to consume the body before the final
   // response gets to the caller.
   //

   return new BufferingClientHttpRequestFactory(scrf);
}
项目:OpenConext-pdp    文件:UrlResourceServiceRegistry.java   
public UrlResourceServiceRegistry(
    String username,
    String password,
    String idpRemotePath,
    String spRemotePath,
    int refreshInMinutes) throws MalformedURLException {
    super(false);

    this.idpUrlResource = new BasicAuthenticationUrlResource(idpRemotePath, username, password);
    this.spUrlResource = new BasicAuthenticationUrlResource(spRemotePath, username, password);

    this.idpRemotePath = idpRemotePath;
    this.spRemotePath = spRemotePath;
    this.refreshInMinutes = refreshInMinutes;

    SimpleClientHttpRequestFactory requestFactory = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
    requestFactory.setConnectTimeout(5 * 1000);

    schedule(this.refreshInMinutes, TimeUnit.MINUTES);
    doInitializeMetadata(true);
}
项目:srccode    文件:LocalDefaultHttpClient.java   
private ResponseEntity<String> request(UriComponentsBuilder uriComponentsBuilder, HttpMethod method, int connectTimeout, int readTimeout) throws RestClientException
{
    LOGGER.info(uriComponentsBuilder.build(false).encode().toUriString()+" (ConenectTimeout="+connectTimeout+" ReadTimeout="+readTimeout+")");

    //proxy support
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    if (LOGGER.isDebugEnabled()) LOGGER.debug("Http PROXY settings:"+HttpProxyGlobalConfigReader.getHttpProxy());
    if (HttpProxyGlobalConfigReader.getHttpProxy()!=null)
        factory.setProxy(HttpProxyGlobalConfigReader.getHttpProxy());
    factory.setConnectTimeout(connectTimeout);
    factory.setReadTimeout(readTimeout);


    RestTemplate restTemplate = new RestTemplate();

    restTemplate.setRequestFactory(factory);
    HttpHeaders requestHeaders = new HttpHeaders();
    HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);
    return restTemplate.exchange(uriComponentsBuilder.build(false).encode().toUriString(), method, requestEntity, String.class);  
}
项目:denv    文件:ContainerizedSynchronizationService.java   
@Autowired
protected ContainerizedSynchronizationService(EnvironmentRepository environmentRepository,
                                              EnvironmentConfigRepository environmentConfigRepository,
                                              VersionRepository versionRepository,
                                              EnvironmentService environmentService,
                                              ImageManager imageManager,
                                              ContainerManager containerManager,
                                              NamingStrategy namingStrategy,
                                              VersionService versionManager,
                                              ContainerVersioningPolicy versioningPolicy) {
    super(environmentRepository, environmentConfigRepository, versionRepository);
    this.environmentService = environmentService;
    this.imageManager = imageManager;
    this.containerManager = containerManager;
    this.namingStrategy = namingStrategy;
    this.versionManager = versionManager;
    this.versioningPolicy = versioningPolicy;
    this.clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
}
项目:appengine    文件:UserRestFT.java   
@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));
}
项目:callerid-for-android    文件:RestTemplateProvider.java   
public RestTemplate get() {
    final RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());

    //remove the existing MappingJacksonHttpMessageConverter - we're going to be using our own
    final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator();
    while(iterator.hasNext()){
        final HttpMessageConverter<?> converter = iterator.next();
        if(converter instanceof MappingJackson2HttpMessageConverter){
            iterator.remove();
        }
    }

    //handle json data
    final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    jsonConverter.setObjectMapper(jsonObjectMapper);
    restTemplate.getMessageConverters().add(0,jsonConverter);

    return restTemplate;
}
项目:xm-uaa    文件:TemplateUtil.java   
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;
}
项目:openssp    文件:JsonDataProviderConnector.java   
private T connect(final PathBuilder config) throws RestClientException {
    final RestTemplate restTemplate = new RestTemplate(httpMessageConverters);
    final SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
    rf.setReadTimeout(2000);
    rf.setConnectTimeout(2000);
    config.addParam("t", RestfulContext.getToken());
    final ResponseEntity<T> re = restTemplate.getForEntity(config.buildEndpointURI(), dtoType);
    return re.getBody();
}
项目:openssp    文件:LoginService.java   
/**
 * Creates a login call to remote webservice.
 * 
 * @param config
 * @return token | RestClientException
 */
public static String loginDataProvider(final PathBuilder config) {
    final MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("u", config.getMaster_user());
    map.add("p", config.getMaster_pw());
    final RestTemplate restTemplate = new RestTemplate();
    final SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
    rf.setReadTimeout(3000);
    rf.setConnectTimeout(30000);
    try {
        final URI uri = new URIBuilder().setScheme("http").setCharset(StandardCharsets.UTF_8).setHost(config
                .getServer()).setPath("/ssp-data-provider/login/token").build();
        final TokenWrapper result = restTemplate.postForObject(uri, map, TokenWrapper.class);
        return result.getToken();
    } catch (final URISyntaxException | RestClientException e) {
        System.out.println("[WARNING] LoginService: " + e.getMessage());
    }

    return null;
}
项目:cf-java-client-sap    文件:CloudFoundryClientTest.java   
/**
 * Self tests that the assert mechanisms with jetty and byteman are properly working. If debugging is needed consider enabling one or
 * more of the following system properties -Dorg.jboss.byteman.verbose=true -Dorg.jboss.byteman.debug=true
 * -Dorg.jboss.byteman.rule.debug=true -Dorg.eclipse.jetty.util.log.class=org .eclipse.jetty.util.log.StdErrLog
 * -Dorg.eclipse.jetty.LEVEL=INFO -Dorg.eclipse.jetty.server.LEVEL=INFO -Dorg.eclipse.jetty.server.handler .ConnectHandler=DEBUG
 * Documentation on byteman at http://downloads.jboss.org/byteman/2.1.3/ProgrammersGuideSinglePage.2.1.3.1.html
 */
@Test
public void checkByteManrulesAndInJvmProxyAssertMechanisms() {
    if (SKIP_INJVM_PROXY) {
        return; // inJvm Proxy test skipped.
    }
    assertTrue(SocketDestHelper.isSocketRestrictionFlagActive());

    RestUtil restUtil = new RestUtil();
    RestTemplate restTemplateNoProxy = restUtil.createRestTemplate(null, CCNG_API_SSL);

    // When called directly without a proxy, expect an exception to be thrown due to byteman rules
    assertNetworkCallFails(restTemplateNoProxy, new HttpComponentsClientHttpRequestFactory());
    // Repeat that with different request factory used in the code as this exercises different byteman rules
    assertNetworkCallFails(restTemplateNoProxy, new SimpleClientHttpRequestFactory());
    // And with the actual one used by RestUtil, without a proxy configured
    assertNetworkCallFails(restTemplateNoProxy, restUtil.createRequestFactory(null, CCNG_API_SSL));

    // Test with the in-JVM proxy configured
    HttpProxyConfiguration localProxy = new HttpProxyConfiguration("127.0.0.1", inJvmProxyPort);
    RestTemplate restTemplate = restUtil.createRestTemplate(localProxy, CCNG_API_SSL);

    restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, null);

    // then executes fine, and the jetty proxy indeed received one request
    assertEquals("expected network calls to make it through the inJvmProxy.", 1, nbInJvmProxyRcvReqs.get());
    nbInJvmProxyRcvReqs.set(0); // reset for next test

    assertTrue(SocketDestHelper.isActivated());
    assertFalse("expected some installed rules, got:" + SocketDestHelper.getInstalledRules(),
        SocketDestHelper.getInstalledRules().isEmpty());
}
项目:devops-cstack    文件:RestUtils.java   
/**
 * 
 * /** sendPostCommand
 *
 * @param url
 * @param parameters
 * @return
 * @throws ClientProtocolException
 */
public Map<String, Object> sendPostForUpload(String url, Map<String, Object> parameters) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setBufferRequestBody(false);

    RestTemplate restTemplate = new RestTemplate(requestFactory);
    List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters();
    mc.add(new MappingJackson2HttpMessageConverter());
    restTemplate.setMessageConverters(mc);

    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(parameters);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    HttpEntity<Object> request = new HttpEntity<Object>(postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put(CONTENT_TYPE, contentType);
    response.put(STATUS_CODE, statusCode);
    response.put(BODY, body);

    return response;

}
项目:geocoder-microservices    文件:RestTemplateConfig.java   
@Bean
public RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

    Proxy proxy= new Proxy(Type.HTTP, new InetSocketAddress("vip-px.main.aviva.eu.corp", 8080));
    requestFactory.setProxy(proxy);
    return new RestTemplate(requestFactory);
   // return new RestTemplate();
}
项目:xm-ms-entity    文件:TemplateUtil.java   
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;
}
项目:mot-automated-testsuite    文件:DataServerManager.java   
/**
 * 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;
    }
}
项目:lams    文件:AsyncRestTemplate.java   
/**
 * Create a new instance of the {@code AsyncRestTemplate} using the given
 * {@link AsyncTaskExecutor}.
 * <p>This constructor uses a {@link SimpleClientHttpRequestFactory} in combination
 * with the given {@code AsyncTaskExecutor} for asynchronous execution.
 */
public AsyncRestTemplate(AsyncListenableTaskExecutor taskExecutor) {
    Assert.notNull(taskExecutor, "AsyncTaskExecutor must not be null");
    SimpleClientHttpRequestFactory requestFactory =
            new SimpleClientHttpRequestFactory();
    requestFactory.setTaskExecutor(taskExecutor);
    this.syncTemplate = new RestTemplate(requestFactory);
    setAsyncRequestFactory(requestFactory);
}
项目:BreakfastServer    文件:PmsRestClient.java   
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;
}
项目:spring-rest-basis    文件:LoggingRequestFactoryFactory.java   
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
    );
}
项目:spring-rest-basis    文件:Zg2proRestTemplate.java   
@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
            )
    );
}
项目:spring-rest-basis    文件:LogsTest.java   
/**
 * 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);
}
项目:spring-credhub    文件:ClientHttpRequestFactoryFactory.java   
static ClientHttpRequestFactory usingJdk(ClientOptions options) {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

    if (options.getConnectionTimeout() != null) {
        factory.setConnectTimeout(options.getConnectionTimeout());
    }
    if (options.getReadTimeout() != null) {
        factory.setReadTimeout(options.getReadTimeout());
    }

    return factory;
}
项目:spring-cloud-gcp    文件:GoogleConfigPropertySourceLocator.java   
GoogleConfigEnvironment getRemoteEnvironment() throws IOException, HttpClientErrorException {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setReadTimeout(this.timeout);
    RestTemplate template = new RestTemplate(requestFactory);
    HttpEntity<Void> requestEntity = getAuthorizedRequest();
    ResponseEntity<GoogleConfigEnvironment> response = template.exchange(
            RUNTIMECONFIG_API_ROOT + ALL_VARIABLES_PATH, HttpMethod.GET, requestEntity,
            GoogleConfigEnvironment.class, this.projectId, this.name, this.profile);

    if (response == null || !response.getStatusCode().is2xxSuccessful()) {
        HttpStatus code = (response == null) ? HttpStatus.BAD_REQUEST : response.getStatusCode();
        throw new HttpClientErrorException(code, "Invalid response from Runtime Configurator API");
    }
    return response.getBody();
}
项目:spring-boot-sms-zenvia    文件:SendSmsService.java   
private RestTemplate buildRestTemplate() {

    LOG.debug("Building Rest Template ...");

    RestTemplate restTemplate = new RestTemplate();
    ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
    return restTemplate;
}
项目:apollo-custom    文件:CtripUserService.java   
private ClientHttpRequestFactory clientHttpRequestFactory() {
  SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  factory.setConnectTimeout(portalConfig.connectTimeout());
  factory.setReadTimeout(portalConfig.readTimeout());

  return factory;
}
项目:apollo-custom    文件:CtripMQService.java   
@PostConstruct
public void init() {
  restTemplate = new RestTemplate();

  SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
  rf.setReadTimeout(portalConfig.readTimeout());
  rf.setConnectTimeout(portalConfig.connectTimeout());

  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setSupportedMediaTypes(
      Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));

  restTemplate.setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter()));

}
项目:log-sink    文件:IntegrationTestConfig.java   
@Bean
public ClientHttpRequestFactory instanceLogsRequestFactory() {
    // Replacing Apache's HttpClient with Spring's simple client in this test, because the Apache one caches
    // connections, tries to reuse the over multiple tests and finally fails becuase WireMock will be reset
    // in each test.
    return new SimpleClientHttpRequestFactory();
}
项目:oma-riista-web    文件:AbstractMMLServiceTest.java   
protected static MMLWebFeatureServiceRequestTemplate createRequestTemplate() throws IOException {
    ClassPathResource classPathResource = new ClassPathResource("configuration/application.properties");
    ResourcePropertySource propertySource = new ResourcePropertySource(classPathResource);
    String uri = propertySource.getProperty("wfs.mml.uri").toString();
    String username = propertySource.getProperty("wfs.mml.username").toString();
    String password = propertySource.getProperty("wfs.mml.password").toString();

    MMLProperties mmlProperties = new MMLProperties(uri, username, password);
    ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

    return new MMLWebFeatureServiceRequestTemplate(mmlProperties, requestFactory);
}
项目:xroad-catalog    文件:ApplicationConfiguration.java   
private void setTimeout(RestTemplate restTemplate, int timeout) {
    //Explicitly setting ClientHttpRequestFactory instance to
    //SimpleClientHttpRequestFactory instance to leverage
    //set*Timeout methods
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(timeout);
    rf.setConnectTimeout(timeout);
}
项目:apollo    文件:CtripUserService.java   
private ClientHttpRequestFactory clientHttpRequestFactory() {
  SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  factory.setConnectTimeout(portalConfig.connectTimeout());
  factory.setReadTimeout(portalConfig.readTimeout());

  return factory;
}
项目:apollo    文件:CtripMQService.java   
@PostConstruct
public void init() {
  restTemplate = new RestTemplate();

  SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
  rf.setReadTimeout(portalConfig.readTimeout());
  rf.setConnectTimeout(portalConfig.connectTimeout());

  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setSupportedMediaTypes(
      Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));

  restTemplate.setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter()));

}
项目:spring4-understanding    文件:AsyncRestTemplate.java   
/**
 * Create a new instance of the {@code AsyncRestTemplate} using the given
 * {@link AsyncTaskExecutor}.
 * <p>This constructor uses a {@link SimpleClientHttpRequestFactory} in combination
 * with the given {@code AsyncTaskExecutor} for asynchronous execution.
 */
public AsyncRestTemplate(AsyncListenableTaskExecutor taskExecutor) {
    Assert.notNull(taskExecutor, "AsyncTaskExecutor must not be null");
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setTaskExecutor(taskExecutor);
    this.syncTemplate = new RestTemplate(requestFactory);
    setAsyncRequestFactory(requestFactory);
}