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


Java HttpClientBuilder.build方法代码示例

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


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

示例1: parse

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
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<>();
}
 
开发者ID:IzzelAliz,项目名称:LCL,代码行数:24,代码来源:McbbsParser.java

示例2: testPost

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
@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"));
    }
}
 
开发者ID:daishicheng,项目名称:outcomes,代码行数:17,代码来源:RfiController.java

示例3: setProxy

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
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();
}
  }
 
开发者ID:spyder007,项目名称:teamcity-msteams-notifier,代码行数:20,代码来源:MsTeamsNotificationImpl.java

示例4: httpClientAttachmentTest

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
@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();
        }
    }
}
 
开发者ID:allure-framework,项目名称:allure-java,代码行数:17,代码来源:HttpClientAttachmentTest.java

示例5: shouldCreateRequestAttachment

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
@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");
}
 
开发者ID:allure-framework,项目名称:allure-java,代码行数:26,代码来源:AllureHttpClientTest.java

示例6: connect

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
@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
        }
    };
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:18,代码来源:DropboxSession.java

示例7: makeHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
/**
 * 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();
}
 
开发者ID:webmate-io,项目名称:webmate-sdk-java,代码行数:21,代码来源:WebmateApiClient.java

示例8: runSparqlQuery

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:Smartlogic-Semaphore-Limited,项目名称:Java-APIs,代码行数:32,代码来源:OEModelEndpoint.java

示例9: main

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
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.

}
 
开发者ID:wellsb1,项目名称:fort_w,代码行数:45,代码来源:TestHttpClient45IgnoreSSLErrors.java

示例10: connect

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
@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());
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:9,代码来源:B2Session.java

示例11: prepareRestTemplate

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的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

示例12: createHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
/**
 * 获取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();
}
 
开发者ID:fengzhizi715,项目名称:NetDiscovery,代码行数:45,代码来源:HttpManager.java

示例13: initRestTemplate

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的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

示例14: createHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
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();
}
 
开发者ID:Precedented,项目名称:Precedented,代码行数:14,代码来源:WatsonRank.java

示例15: createHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
private CloseableHttpClient createHttpClient(){
    HttpClientBuilder builder =  HttpClientBuilder.create();
    return builder.build();
}
 
开发者ID:fcibook,项目名称:QuickHttp,代码行数:5,代码来源:QuickHttpController.java


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