org.springframework.http.client.SimpleClientHttpRequestFactory Java Examples

The following examples show how to use org.springframework.http.client.SimpleClientHttpRequestFactory. 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: ConfigServicePropertySourceLocator.java    From spring-cloud-config with Apache License 2.0 9 votes vote down vote up
private RestTemplate getSecureRestTemplate(ConfigClientProperties client) {
	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
	if (client.getRequestReadTimeout() < 0) {
		throw new IllegalStateException("Invalid Value for Read Timeout set.");
	}
	if (client.getRequestConnectTimeout() < 0) {
		throw new IllegalStateException("Invalid Value for Connect Timeout set.");
	}
	requestFactory.setReadTimeout(client.getRequestReadTimeout());
	requestFactory.setConnectTimeout(client.getRequestConnectTimeout());
	RestTemplate template = new RestTemplate(requestFactory);
	Map<String, String> headers = new HashMap<>(client.getHeaders());
	if (headers.containsKey(AUTHORIZATION)) {
		headers.remove(AUTHORIZATION); // To avoid redundant addition of header
	}
	if (!headers.isEmpty()) {
		template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
				new GenericRequestHeaderInterceptor(headers)));
	}

	return template;
}
 
Example #2
Source File: SentinelRuleLocator.java    From Sentinel with Apache License 2.0 7 votes vote down vote up
private RestTemplate getSecureRestTemplate(ConfigClientProperties client) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    if (client.getRequestReadTimeout() < 0) {
        throw new IllegalStateException("Invalid Value for Read Timeout set.");
    }
    requestFactory.setReadTimeout(client.getRequestReadTimeout());
    RestTemplate template = new RestTemplate(requestFactory);
    Map<String, String> headers = new HashMap<>(client.getHeaders());
    if (headers.containsKey(AUTHORIZATION)) {
        // To avoid redundant addition of header
        headers.remove(AUTHORIZATION);
    }
    if (!headers.isEmpty()) {
        template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
            new GenericRequestHeaderInterceptor(headers)));
    }

    return template;
}
 
Example #3
Source File: RestTemplateConfig.java    From SpringBootLearn with Apache License 2.0 6 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setConnectTimeout(15000);
    factory.setReadTimeout(5000);
    return factory;
}
 
Example #4
Source File: RestfulTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    log.info("=============================={}.{}==============================",
            this.getClass().getSimpleName(),
            this.testName.getMethodName());

    this.url = "http://localhost:" + this.listenPort + "/weevent-broker/rest/";

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    this.rest = new RestTemplate(requestFactory);

    this.rest.exchange(url + "open?topic={topic}&groupId={groupId}", HttpMethod.GET, null, new ParameterizedTypeReference<BaseResponse<Boolean>>() {
    }, this.topicName, WeEvent.DEFAULT_GROUP_ID);

    SendResult sendResult = rest.getForEntity(url + "publish?topic={topic}&content={content}", SendResult.class, this.topicName,
            this.content).getBody();
    Assert.assertNotNull(sendResult);
    this.eventId = sendResult.getEventId();
}
 
Example #5
Source File: RestTemplateProvider.java    From callerid-for-android with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: Rest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    System.out.println("This is WeEvent restful sample.");
    try {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        RestTemplate rest = new RestTemplate(requestFactory);

        // ensure topic exist "com.weevent.test"
        String topic = "com.weevent.test";
        ResponseEntity<BaseResponse<Boolean>> rsp = rest.exchange("http://localhost:7000/weevent-broker/rest/open?topic={topic}&groupId={groupId}", HttpMethod.GET, null, new ParameterizedTypeReference<BaseResponse<Boolean>>() {
        }, topic, WeEvent.DEFAULT_GROUP_ID);
        System.out.println(rsp.getBody().getData());

        // publish event to topic "com.weevent.test"
        SendResult sendResult = rest.getForEntity("http://localhost:7000/weevent-broker/rest/publish?topic={topic}&groupId={groupId}&content={content}",
                SendResult.class,
                topic,
                WeEvent.DEFAULT_GROUP_ID,
                "hello WeEvent".getBytes(StandardCharsets.UTF_8)).getBody();
        System.out.println(sendResult);
    } catch (RestClientException e) {
        e.printStackTrace();
    }
}
 
Example #7
Source File: AllureRestTemplateTest.java    From allure-java with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: XxxTest.java    From x7 with Apache License 2.0 6 votes vote down vote up
public ViewEntity testRestTemplate(){

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(60000);
        requestFactory.setReadTimeout(60000);

        String url = "http://127.0.0.1:8868/xxx/test/rest";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("TX_XID", "eg564ssasdd");

        CatTest cat = new CatTest();
        cat.setType("TEST_CAT");
        HttpEntity<CatTest> requestEntity = new HttpEntity<CatTest>(cat,httpHeaders);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        ResponseEntity<String> result = restTemplate.postForEntity(url, requestEntity,String.class);

        return ViewEntity.ok(result);
    }
 
Example #9
Source File: ClientHttpRequestFactoryFactory.java    From spring-credhub with Apache License 2.0 6 votes vote down vote up
static ClientHttpRequestFactory usingJdk(ClientOptions options) {
	if (usingCustomCerts(options)) {
		logger.warn("Trust material will not be configured when using "
				+ "java.net.HttpUrlConnection. Use an alternate HTTP Client "
				+ "(Apache HttpComponents HttpClient, OkHttp3, or Netty) when "
				+ "configuring CA certificates.");
	}

	SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

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

	return factory;
}
 
Example #10
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: RequestMappingViewResolutionIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-15291
public void redirect() throws Exception {
	SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() {
		@Override
		protected void prepareConnection(HttpURLConnection conn, String method) throws IOException {
			super.prepareConnection(conn, method);
			conn.setInstanceFollowRedirects(false);
		}
	};

	URI uri = new URI("http://localhost:" + this.port + "/redirect");
	RequestEntity<Void> request = RequestEntity.get(uri).accept(MediaType.ALL).build();
	ResponseEntity<Void> response = new RestTemplate(factory).exchange(request, Void.class);

	assertEquals(HttpStatus.SEE_OTHER, response.getStatusCode());
	assertEquals("/", response.getHeaders().getLocation().toString());
}
 
Example #12
Source File: RestProxyTemplate.java    From orders with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: EmptyEntityTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldPassEmptyEntity() {
    driver.addExpectation(onRequestTo("/").withHeader("Passed", "true"),
            giveEmptyResponse());

    final Http http = Http.builder()
            .executor(executor)
            .requestFactory(new SimpleClientHttpRequestFactory())
            .baseUrl(driver.getBaseUrl())
            .plugin(new Plugin() {
                @Override
                public RequestExecution aroundNetwork(final RequestExecution execution) {
                    return arguments -> {
                        assertTrue(arguments.getEntity().isEmpty());
                        return execution.execute(arguments.withHeader("Passed", "true"));
                    };
                }
            })
            .build();

    http.get("/")
            .call(pass())
            .join();

    driver.verify();
}
 
Example #14
Source File: AbstractTwitterInboundChannelAdapter.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
/**
 * The read timeout for the underlying URLConnection to the twitter stream.
 */
public void setReadTimeout(int millis) {
	// Hack to get round Spring's dynamic loading of http client stuff
	ClientHttpRequestFactory f = getRequestFactory();
	if (f instanceof SimpleClientHttpRequestFactory) {
		((SimpleClientHttpRequestFactory) f).setReadTimeout(millis);
	}
	else {
		((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis);
	}
}
 
Example #15
Source File: EmptyEntityTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldPassNonEmptyEntity() {
    driver.addExpectation(onRequestTo("/").withMethod(POST).withHeader("Passed", "true"),
            giveEmptyResponse());

    final Http http = Http.builder()
            .executor(executor)
            .requestFactory(new SimpleClientHttpRequestFactory())
            .baseUrl(driver.getBaseUrl())
            .plugin(new Plugin() {
                @Override
                public RequestExecution aroundNetwork(final RequestExecution execution) {
                    return arguments -> {
                        assertFalse(arguments.getEntity().isEmpty());
                        return execution.execute(arguments.withHeader("Passed", "true"));
                    };
                }
            })
            .build();

    http.post("/")
            .body(emptyMap())
            .call(pass())
            .join();

    driver.verify();
}
 
Example #16
Source File: AsyncRestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: CtripMQService.java    From apollo with Apache License 2.0 5 votes vote down vote up
@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_UTF8, MediaType.APPLICATION_OCTET_STREAM));

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

}
 
Example #18
Source File: ThreadAffinityTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void syncBlocking() {
    final ConfigurationStage stage = Http.builder()
            .executor(Runnable::run)
            .requestFactory(new SimpleClientHttpRequestFactory());

    test(stage, "main", "main", "main");
}
 
Example #19
Source File: YandexSearchProvider.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
private void init() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setConnectTimeout((int) HTTP_TIMEOUT_DURATION.toMillis());
    requestFactory.setReadTimeout((int) HTTP_TIMEOUT_DURATION.toMillis());

    var yandexProxy = workerProperties.getAudio().getYandexProxy();
    if (StringUtils.isNotEmpty(yandexProxy.getHost())) {
        requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(yandexProxy.getHost(), yandexProxy.getPort())));
    }

    this.restTemplate = new RestTemplate(requestFactory);
}
 
Example #20
Source File: SimpleHttpRequester.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance of the SimpleHttpRequester class with the specified connection timeout.
 * <p/>
 * @param connectTimeout an integer value specifying the timeout value in milliseconds for establishing the HTTP
 * connection to the HTTP server.
 */
public SimpleHttpRequester(final int connectTimeout) {
  final SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();

  clientHttpRequestFactory.setConnectTimeout(connectTimeout);

  this.restTemplate = new RestTemplate(clientHttpRequestFactory);
}
 
Example #21
Source File: GoogleSearchProviderImpl.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private void setTimeout(RestTemplate restTemplate, int connectTimeout, int readTimeout) {
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(readTimeout);
    rf.setConnectTimeout(connectTimeout);
}
 
Example #22
Source File: RestTemplateConfig.java    From withme3.0 with MIT License 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);
    factory.setConnectTimeout(5000);
    return factory;
}
 
Example #23
Source File: AsyncRestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #24
Source File: RestTemplateConfig.java    From withme3.0 with MIT License 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);
    factory.setConnectTimeout(5000);
    return factory;
}
 
Example #25
Source File: SystemConfig.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
@Bean
public RestTemplate buildRestTemplate() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(10000);
    factory.setConnectTimeout(15000);
    return new RestTemplate(factory);
}
 
Example #26
Source File: SimpleHttpRequester.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance of the SimpleHttpRequester class with the specified connection timeout.
 * <p/>
 * @param connectTimeout an integer value specifying the timeout value in milliseconds for establishing the HTTP
 * connection to the HTTP server.
 */
public SimpleHttpRequester(final int connectTimeout) {
  final SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();

  clientHttpRequestFactory.setConnectTimeout(connectTimeout);

  this.restTemplate = new RestTemplate(clientHttpRequestFactory);
}
 
Example #27
Source File: ThreadAffinityTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void asyncBlocking() {
    final ConfigurationStage stage = Http.builder()
            .executor(Executors.newSingleThreadExecutor(threadFactory("process")))
            .requestFactory(new SimpleClientHttpRequestFactory());

    test(stage, "process", "process", "process");
}
 
Example #28
Source File: RestTemplateConfig.java    From withme3.0 with MIT License 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);
    factory.setConnectTimeout(5000);
    return factory;
}
 
Example #29
Source File: RequestCompressionPluginTest.java    From riptide with MIT License 5 votes vote down vote up
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) {
    return Stream.of(
            new SimpleClientHttpRequestFactory(),
            // new Netty4ClientHttpRequestFactory(), # broken, see #823
            new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()),
            new ApacheClientHttpRequestFactory(HttpClients.createDefault(), Mode.BUFFERING),
            new ApacheClientHttpRequestFactory(HttpClients.createDefault(), Mode.STREAMING)
    ).map(Arguments::of);
}
 
Example #30
Source File: RestTemplateConfig.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);//ms
    factory.setConnectTimeout(15000);//ms
    return factory;
}