Java Code Examples for org.apache.http.impl.client.HttpClientBuilder.build()

The following are Jave code examples for showing how to use build() of the org.apache.http.impl.client.HttpClientBuilder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: LCL   File: McbbsParser.java   Source Code and License Vote up 6 votes
public static List<ThreadPost> parse(String[] param) throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    try (CloseableHttpClient client = builder.build()) {
        StringBuilder url = new StringBuilder("http://www.mcbbs.net/forum.php?");
        for (String para : param)
            url.append(para).append("&");
        url.append("mod=forumdisplay&mobile=2");
        HttpGet get = new HttpGet(url.toString());
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();
        get.setConfig(requestConfig);
        get.setHeader("User-Agent",
                "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Mobile Safari/537.36");
        get.setHeader("Connection", "keep-alive");
        try (CloseableHttpResponse response = client.execute(get)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String html = EntityUtils.toString(entity, "utf-8");
                return parseXml(html);
            }
        }
    }
    return new ArrayList<>();
}
 
Example 2
Project: outcomes   File: RfiController.java   Source Code and License Vote up 6 votes
@RequestMapping(value = "/rfi/weChat", method = RequestMethod.POST)
public void testPost(@RequestParam(value = "code", required = false) String code) throws IOException {
    System.out.println(code);
    System.out.println("====================================");

    String url = "https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect";
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
    CloseableHttpClient client = builder.build();
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    InputStream inputStream = response.getEntity().getContent();
    byte [] tt = new byte[1024];
    while (inputStream.read(tt) != -1) {
        System.out.println(new String(tt,"utf-8"));
    }
}
 
Example 3
Project: teamcity-msteams-notifier   File: MsTeamsNotificationImpl.java   Source Code and License Vote up 6 votes
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
      
if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
          HttpClientBuilder clientBuilder = HttpClients.custom()
              .useSystemProperties()
              .setProxy(new HttpHost(proxyHost, proxyPort, "http"));
              
          if (credentials != null) {
              CredentialsProvider credsProvider = new BasicCredentialsProvider();
              credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
              clientBuilder.setDefaultCredentialsProvider(credsProvider);
              Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
          }
          
          this.client = clientBuilder.build();
}
  }
 
Example 4
Project: allure-java   File: HttpClientAttachmentTest.java   Source Code and License Vote up 6 votes
@Test
void httpClientAttachmentTest() throws IOException {
    stubFor(get(urlEqualTo("/hello"))
            .willReturn(aResponse()
                    .withBody("Hello world!")));

    final HttpClientBuilder builder = HttpClientBuilder.create()
            .addInterceptorFirst(new AllureHttpClientRequest())
            .addInterceptorLast(new AllureHttpClientResponse());
    try (CloseableHttpClient httpClient = builder.build()) {
        final HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/hello", server.port()));
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            response.getStatusLine().getStatusCode();
        }
    }
}
 
Example 5
Project: allure-java   File: AllureHttpClientTest.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
@Test
public void shouldCreateRequestAttachment() throws Exception {
    final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class);
    final AttachmentProcessor<AttachmentData> processor = mock(AttachmentProcessor.class);

    final HttpClientBuilder builder = HttpClientBuilder.create()
            .addInterceptorLast(new AllureHttpClientRequest(renderer, processor));

    try (CloseableHttpClient httpClient = builder.build()) {
        final HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/hello", server.port()));
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            response.getStatusLine().getStatusCode();
        }
    }

    final ArgumentCaptor<AttachmentData> captor = ArgumentCaptor.forClass(AttachmentData.class);
    verify(processor, times(1))
            .addAttachment(captor.capture(), eq(renderer));

    assertThat(captor.getAllValues())
            .hasSize(1)
            .extracting("url")
            .containsExactly("/hello");
}
 
Example 6
Project: cyberduck   File: DropboxSession.java   Source Code and License Vote up 6 votes
@Override
protected DbxRawClientV2 connect(final HostKeyCallback callback, final LoginCallback prompt) {
    authorizationService = new OAuth2RequestInterceptor(builder.build(this, prompt).build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    final HttpClientBuilder configuration = builder.build(this, prompt);
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(authorizationService));
    final CloseableHttpClient client = configuration.build();
    return new DbxRawClientV2(DbxRequestConfig.newBuilder(useragent.get())
        .withAutoRetryDisabled()
        .withHttpRequestor(new DropboxCommonsHttpRequestExecutor(client)).build(), DbxHost.DEFAULT) {
        @Override
        protected void addAuthHeaders(final List<HttpRequestor.Header> headers) {
            // OAuth Bearer added in interceptor
        }
    };
}
 
Example 7
Project: webmate-sdk-java   File: WebmateApiClient.java   Source Code and License Vote up 6 votes
/**
 * Creates new HttpClient for interacting with webmate API.
 *
 * @param authInfo    authentication information (email address + token)
 * @param environment API endpoint address
 * @return new HttpClient to be used by Service clients.
 */
private static HttpClient makeHttpClient(WebmateAuthInfo authInfo, WebmateEnvironment environment, HttpClientBuilder httpClientBuilder) {

    httpClientBuilder.setUserAgent(WEBMATE_JAVASDK_USERAGENT);

    List<Header> headers = new ArrayList<>();

    headers.add(new BasicHeader(WEBMATE_USER_HEADERKEY, authInfo.emailAddress));
    headers.add(new BasicHeader(WEBMATE_APITOKEN_HEADERKEY, authInfo.apiKey));
    headers.add(new BasicHeader("Content-Type", "application/json"));

    httpClientBuilder.setDefaultHeaders(headers);
    return httpClientBuilder.build();
}
 
Example 8
Project: Java-APIs   File: OEModelEndpoint.java   Source Code and License Vote up 6 votes
/**
 * Runs the SPARQL query and returns a detached ResultSet.
 * If you have a large query, use the same technique inline to stream results and save memory.
 *
 * @param sparql
 * @return
 */
public ResultSet runSparqlQuery(String sparql) {

  if (logger.isDebugEnabled())
    logger.debug("run SPARQL query: {}", sparql);

  Query query = QueryFactory.create(sparql);
  ResultSet results = null;
  HttpClientBuilder clientBuilder = HttpClientBuilder.create();

  setCloudAuthHeaderIfConfigured(clientBuilder);

  if (proxyHost != null && proxyPort != null) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    clientBuilder.setProxy(proxy);
  }

  try (CloseableHttpClient client = clientBuilder.build();
       QueryExecution qe = QueryExecutionFactory.sparqlService(buildSPARQLUrl().toString(), query, client)) {
    results = ResultSetFactory.copyResults(qe.execSelect());
  } catch (IOException ioe) {
    throw new RuntimeException("IOException.", ioe);
  }
  return results;
}
 
Example 9
Project: cyberduck   File: B2Session.java   Source Code and License Vote up 5 votes
@Override
public B2ApiClient connect(final HostKeyCallback key, final LoginCallback prompt) throws BackgroundException {
    final HttpClientBuilder configuration = builder.build(this, prompt);
    configuration.setServiceUnavailableRetryStrategy(retryHandler = new B2ErrorResponseInterceptor(
        this));
    configuration.addInterceptorLast(retryHandler);
    return new B2ApiClient(configuration.build());
}
 
Example 10
Project: spring-cloud-dashboard   File: HttpClientUtils.java   Source Code and License Vote up 5 votes
/**
 * 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);
}
 
Example 11
Project: NetDiscovery   File: HttpManager.java   Source Code and License Vote up 5 votes
/**
 * 获取Http客户端连接对象
 * @param timeOut 超时时间
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客户端连接对象
 */
public CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 创建Http请求配置参数
    RequestConfig.Builder builder = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 创建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(new RetryHandler())
            // 配置连接池管理对象
            .setConnectionManager(connManager);

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
Example 12
Project: admin-shiro   File: RestTemplateConfig.java   Source Code and License Vote up 5 votes
/**
 * 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;

}
 
Example 13
Project: Precedented   File: WatsonRank.java   Source Code and License Vote up 5 votes
private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()), new UsernamePasswordCredentials(USERNAME, PASSWORD));
    final HttpClientBuilder builder = HttpClientBuilder.create()
        .setMaxConnTotal(128)
        .setMaxConnPerRoute(32)
        .setDefaultRequestConfig(RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
        .setDefaultCredentialsProvider(credentialsProvider)
        .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}
 
Example 14
Project: QuickHttp   File: QuickHttpController.java   Source Code and License Vote up 4 votes
private CloseableHttpClient createHttpClient(){
    HttpClientBuilder builder =  HttpClientBuilder.create();
    return builder.build();
}
 
Example 15
Project: fort_w   File: TestHttpClient45IgnoreSSLErrors.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception
{
   HttpClientBuilder b = HttpClientBuilder.create();

   // setup a Trust Strategy that allows all certificates.
   //
   SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
      {
         public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
         {
            return true;
         }
      }).build();
   b.setSslcontext(sslContext);

   // don't check Hostnames, either.
   //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
   HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

   // here's the special part:
   //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
   //      -- and create a Registry, to register it.
   //
   SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
   Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();

   // now, we create connection-manager using our Registry.
   //      -- allows multi-threaded use
   PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
   b.setConnectionManager(connMgr);

   // finally, build the HttpClient;
   //      -- done!
   HttpClient client = b.build();

   HttpGet get = new HttpGet("https://cpj.org");
   //get.setFollowRedirects(true);

   HttpResponse response = client.execute(get);
   HttpEntity entity = response.getEntity();
   
   //if you got this far, you made it.

}
 
Example 16
Project: TradingRobot   File: Trading.java   Source Code and License Vote up 4 votes
public int setTakeProfitPrice(double lossAmmount, int numOfUnits, boolean buy) {
	Trade t = getTrade();
	double takeProfitPrice = t.getOpeningPrice();
	double usdGbp = getUsdGbp();
	double profitNeeded;
	double distanceBetweenOpenPriceAndTakeProfit = 0;
	if (lossAmmount < 0) {
		//get the absolute value of the loss amount
		profitNeeded = Math.abs(lossAmmount);
		//add 5%
		profitNeeded += profitNeeded * 0.05;
		//add �1
		profitNeeded += 1.0;
	}
	else {
		profitNeeded = 1-lossAmmount;
	}
	
	for (double i=0.00001; i<Double.MAX_VALUE; i += 0.00001) {
		if (i*usdGbp*numOfUnits >= profitNeeded) {
			distanceBetweenOpenPriceAndTakeProfit = i;
			break;
		}
	}
	if (buy) takeProfitPrice += distanceBetweenOpenPriceAndTakeProfit;
	else takeProfitPrice -= distanceBetweenOpenPriceAndTakeProfit;
	takeProfitPrice = round(takeProfitPrice, 5);
	
	//Modifying Trade
	
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpPut request = new HttpPut(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/trades/"+t.getId()+"/orders");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	request.addHeader("Content-Type", "application/json");
	JSONObject takeProfitObject = new JSONObject();
	JSONObject takeProfitDetailsObject = new JSONObject();
	takeProfitDetailsObject.put("price", String.valueOf(takeProfitPrice));
	takeProfitDetailsObject.put("timeInForce", "GTC");
	takeProfitObject.put("takeProfit", takeProfitDetailsObject);
    System.out.println("Take Profit Price: "+takeProfitPrice);
	try {
		HttpEntity entity = new StringEntity(takeProfitObject.toString());
		request.setEntity(entity);
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	try {
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject resultJson = new JSONObject(result.toString());
		System.out.println(resultJson);
		return response.getStatusLine().getStatusCode();
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return 0;
}
 
Example 17
Project: hrrs   File: ApacheHttpClientFactory.java   Source Code and License Vote up 4 votes
public CloseableHttpClient create() {
    RequestConfig requestConfig = createRequestConfig();
    HttpClientConnectionManager connectionManager = createConnectionManager();
    HttpClientBuilder httpClientBuilder = HttpClients
            .custom()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager);
    setRedirectStrategy(httpClientBuilder);
    return httpClientBuilder.build();
}
 
Example 18
Project: TradingRobot   File: Trading.java   Source Code and License Vote up 4 votes
public int buyOrSellAtMarketRate(int unit, double stopLossPrice, String buyOrSell) {
	//statuses: 0: No trade is open 1:There is a trade open already 200: A trade was closed
	int closeTradeStatus = closeExistingTrade(buyOrSell);
	if (closeTradeStatus == 1) return 0;
	if (closeTradeStatus == 200) {
		//Adjust take profit to reflect the loss/profit from the closed trade
		//1 means resend the order
		return 1;
	}
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpPost request = new HttpPost(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/orders");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	request.addHeader("Content-Type", "application/json");
	JSONObject requestOrderObject = new JSONObject();
	JSONObject requestStopLossObject = new JSONObject();
	JSONObject requestObject = new JSONObject();
	requestStopLossObject.put("price", String.valueOf(stopLossPrice));
	requestStopLossObject.put("timeInForce", "GTC");
	requestOrderObject.put("instrument", "EUR_USD");
	requestOrderObject.put("units", (buyOrSell.equals("buy") ? "" : "-")+String.valueOf(unit));
	requestOrderObject.put("timeInForce", "FOK");
	requestOrderObject.put("type", "MARKET");
	requestOrderObject.put("positionFill", "DEFAULT");
	requestOrderObject.put("stopLossOnFill", requestStopLossObject);
	requestObject.put("order", requestOrderObject);
	System.out.println(requestObject.toString());
	try {
		HttpEntity entity = new StringEntity(requestObject.toString());
		request.setEntity(entity);
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	try {
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject resultJson = new JSONObject(result.toString());
		System.out.println(resultJson.toString());
		Logger.logString(resultJson.toString());
		return response.getStatusLine().getStatusCode();
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	return 0;
}
 
Example 19
Project: ats-framework   File: HttpClient.java   Source Code and License Vote up 4 votes
protected void initialzeInternalClient() {

        if (!needsInternalClientInialization) {
            // internal client is already initialized
            return;
        }

        // release any resources if this client was already used
        close();

        // rebuild the client
        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        // Add this interceptor to get the values of all HTTP headers in the request.
        // Some of them are provided by the user while others are generated by Apache HTTP Components.
        httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
            @Override
            public void process( HttpRequest request, HttpContext context ) throws HttpException,
                                                                            IOException {

                Header[] requestHeaders = request.getAllHeaders();
                actualRequestHeaders = new ArrayList<HttpHeader>();
                for (Header header : requestHeaders) {
                    addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
                }
                if (debugLevel != HttpDebugLevel.NONE) {
                    logHTTPRequest(requestHeaders, request);
                }
            }
        });

        // connect and read timeouts
        httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
                                                               .setConnectTimeout(connectTimeoutSeconds
                                                                                  * 1000)
                                                               .setSocketTimeout(readTimeoutSeconds
                                                                                 * 1000)
                                                               .build());

        // socket buffer size
        if (this.socketBufferSize > 0) {
            httpClientBuilder.setDefaultSocketConfig(SocketConfig.custom()
                                                                 .setRcvBufSize(this.socketBufferSize)
                                                                 .setSndBufSize(this.socketBufferSize)
                                                                 .build());
        }

        // SSL
        if (isOverSsl) {
            setupSSL(httpClientBuilder);
        }

        // setup authentication
        if (!StringUtils.isNullOrEmpty(username)) {
            setupAuthentication(httpClientBuilder);
        }

        // set proxy
        if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null
            && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {

            HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST,
                                          Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            httpClientBuilder.setRoutePlanner(routePlanner);
        }

        // now build the client after we have already set everything needed on the client builder
        httpClient = httpClientBuilder.build();

        // do not come here again until not needed
        needsInternalClientInialization = false;
    }
 
Example 20
Project: tasfe-framework   File: HttpClientTemplate.java   Source Code and License Vote up 4 votes
private HttpClientTemplate() {
    // 长连接保持30秒
    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(timeToLive, TimeUnit.SECONDS);
    // 总连接数
    pollingConnectionManager.setMaxTotal(maxTotal);
    // 同路由的并发数
    pollingConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // 重试次数,默认是3次,没有开启
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, requestSentRetryEnabled));
    // 保持长连接配置,需要在头添加Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    // 参考:http://www.cnblogs.com/sink_cup/archive/2011/03/15/http_user_agent.html
    // 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"));
    // 不需要设置,可能会乱码,请参考:http://www.crifan.com/set_accept_encoding_header_to_gzip_deflate_return_messy_code/
    // 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(connectTimeout);
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(readTimeout);
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(connectionRequestTimeout);
    // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
    if (!bufferRequestBody) {
        clientHttpRequestFactory.setBufferRequestBody(false);
    }
    // 添加内容转换器
    // List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new FastJsonHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter(Charset.forName(charset)));
    messageConverters.add(new ByteArrayHttpMessageConverter());
    super.setMessageConverters(messageConverters);
    super.setRequestFactory(clientHttpRequestFactory);
    super.setErrorHandler(new DefaultResponseErrorHandler());
}