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


Java HttpClientBuilder.create方法代码示例

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


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

示例1: runSparqlUpdate

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
/**
 * @param sparql
 * @return
 */
public boolean runSparqlUpdate(String sparql) {

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

  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()) {
    UpdateRequest update = UpdateFactory.create(sparql, Syntax.syntaxARQ);
    UpdateProcessor processor = UpdateExecutionFactory.createRemoteForm(update, buildSPARQLUrl().toString(), client);
    processor.execute();
  } catch (IOException ioe) {
    throw new RuntimeException("IOException.", ioe);
  }
  return true;
}
 
开发者ID:Smartlogic-Semaphore-Limited,项目名称:Java-APIs,代码行数:28,代码来源:OEModelEndpoint.java

示例2: getHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
/**
 * Get a valid {@link HttpClient} to use, with a valid token.
 * 
 * @param login
 * @return
 */
private CloseableHttpClient getHttpClient(final Boolean login, final HttpUriRequest request)
{
    final HttpClientBuilder builder = HttpClientBuilder.create();
    String key;
    // if (apiClient.getApiToken() == null || apiClient.getApiToken())
    if (login)
    {
        key = apiClient.getApiKey();
    }
    else
    {
        key = apiClient.getApiToken();
    }
    key += ":";
    final byte[] credentials = Base64.encodeBase64(key.getBytes(StandardCharsets.UTF_8));
    final BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
    request.addHeader(authHeader);
    return builder.build();
}
 
开发者ID:lake54,项目名称:groupsio-api-java,代码行数:26,代码来源:BaseResource.java

示例3: testPost

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
@Test
public void testPost() throws IOException {
    String ip = "冰箱冰箱冰箱冰箱冰箱冰箱冰箱";
    // 创建HttpClientBuilder
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // HttpClient
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    // 请求参数
    StringEntity entity = new StringEntity("", DEFAULT_ENCODE);
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
    HttpPost httpPost = new HttpPost("https://m.fangliaoyun.com");
    httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
    //此处区别PC终端类型
    httpPost.addHeader("typeFlg", "9");
    //此处增加浏览器端访问IP
    httpPost.addHeader("x-forwarded-for", ip);
    httpPost.addHeader("Proxy-Client-IP", ip);
    httpPost.addHeader("WL-Proxy-Client-IP", ip);
    httpPost.addHeader("HTTP_CLIENT_IP", ip);
    httpPost.addHeader("X-Real-IP", ip);
    httpPost.addHeader("Host", ip);
    httpPost.setEntity(entity);
    httpPost.setConfig(RequestConfig.DEFAULT);

    HttpResponse httpResponse;
    // post请求
    httpResponse = closeableHttpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    System.out.println(httpEntity.getContent());
    //释放资源
    closeableHttpClient.close();
}
 
开发者ID:MinsxCloud,项目名称:minsx-java-example,代码行数:34,代码来源:RemoteServerClientImpl.java

示例4: getBalance

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
public static double getBalance() {
	String temp;
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpGet request = new HttpGet(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/summary");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	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 accountDetails = new JSONObject(result.toString()).getJSONObject("account");
		temp = accountDetails.getString("balance");
		return Double.parseDouble(temp);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return 0;
}
 
开发者ID:toni8810,项目名称:TradingRobot,代码行数:24,代码来源:Account.java

示例5: HttpUtils

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
private HttpUtils(HttpRequestBase request) {
	this.request = request;

	this.clientBuilder = HttpClientBuilder.create();
	this.isHttps = request.getURI().getScheme().equalsIgnoreCase("https");
	this.config = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);
	this.cookieStore = new BasicCookieStore();

	if (request instanceof HttpPost) {
		this.type = 1;
		this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>());

	} else if (request instanceof HttpGet) {
		this.type = 2;
		this.uriBuilder = new URIBuilder();

	} else if (request instanceof HttpPut) {
		this.type = 3;
		this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>());

	} else if (request instanceof HttpDelete) {
		this.type = 4;
		this.uriBuilder = new URIBuilder();
	}
}
 
开发者ID:swxiao,项目名称:bubble2,代码行数:26,代码来源:HttpUtils.java

示例6: getProxyExecutor

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) {

        prop = decrypt(prop);

        String proxyHost = prop.getProperty("proxyHost");
        int proxyPort = Integer.valueOf(prop.getProperty("proxyPort"));
        String proxyUserDomain = prop.getProperty("proxyUserDomain");
        String proxyUser = prop.getProperty("proxyUser");
        String proxyPassword = prop.getProperty("proxyPassword");

        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
        if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
            credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
        builder.setProxy(proxy);
        builder.setDefaultCredentialsProvider(credsProvider);
        HttpClient.Factory factory = new SimpleHttpClientFactory(builder);
        return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);

    }
 
开发者ID:CognizantQAHub,项目名称:Cognizant-Intelligent-Test-Scripter,代码行数:27,代码来源:RemoteProxy.java

示例7: 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

示例8: getClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
private synchronized CloseableHttpClient getClient() {
    if (client == null) {
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setRedirectStrategy(new AlwaysRedirectRedirectStrategy());
        new HttpClientConfigurer(settings).configure(builder);
        this.client = builder.build();
    }
    return client;
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:10,代码来源:HttpClientHelper.java

示例9: main

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClientBuilder builder = HttpClientBuilder.create();
//		HttpPost post = new HttpPost("http://localhost:8088/refresh");
		HttpPost post = new HttpPost("http://localhost:8888/bus/refresh");
		CloseableHttpResponse response = builder.build().execute(post);
		System.out.println(EntityUtils.toString(response.getEntity()));
	}
 
开发者ID:zhaoqilong3031,项目名称:spring-cloud-samples,代码行数:8,代码来源:ApplicationTests.java

示例10: getHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
private static CloseableHttpClient getHttpClient() {
	HttpClientBuilder hb = HttpClientBuilder.create();
	RequestConfig config = RequestConfig.custom().setConnectTimeout(5000)
			.setConnectionRequestTimeout((int) TimeUnit.HOURS.toMillis(1))
			.setSocketTimeout((int) TimeUnit.HOURS.toMillis(1)).setExpectContinueEnabled(false).build();
	hb.setDefaultRequestConfig(config);
	CloseableHttpClient hc = hb.build();
	return hc;
}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:10,代码来源:HttpTest.java

示例11: closeExistingTrade

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
private int closeExistingTrade(String buyOrSell) {
	Trade t = getTrade();
	long existingTradeId;
	if (t != null) {
		if (t.getBuyOrSell().contentEquals(buyOrSell)) return 1;
		existingTradeId = t.getId();
	}
	else {
		//No trade is open
		return 0;
	}
	
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpPut request = new HttpPut(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/trades/"+existingTradeId+"/close");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	System.out.println(request.getURI());
	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;
	}
	
}
 
开发者ID:toni8810,项目名称:TradingRobot,代码行数:37,代码来源:Trading.java

示例12: fetchData

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
public String fetchData() throws IOException, OEConnectionException {
  String fetchUri = buildOEExportApiUrl();

  HttpClientBuilder clientBuilder = HttpClientBuilder.create();
  setCloudAuthHeaderIfConfigured(clientBuilder);
  try (CloseableHttpClient httpClient = clientBuilder.build()) {
    HttpGet httpGet = new HttpGet(fetchUri);

    HttpResponse response = httpClient.execute(httpGet);
    if (response == null) throw new OEConnectionException("Null response from http client: " + fetchUri);
    if (response.getStatusLine() == null)
      throw new OEConnectionException("Null status line from http client: " + fetchUri);


    int statusCode = response.getStatusLine().getStatusCode();

    if (logger.isDebugEnabled())
      logger.debug("HTTP request complete: " + statusCode + " " + fetchUri);

    if (statusCode != HttpStatus.SC_OK) {
      throw new OEConnectionException("Status code " + statusCode + " received from URL: " + fetchUri);
    }

    HttpEntity entity = response.getEntity();

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    entity.writeTo(byteArrayOutputStream);
    return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
  }
}
 
开发者ID:Smartlogic-Semaphore-Limited,项目名称:Java-APIs,代码行数:31,代码来源:OEModelEndpoint.java

示例13: getTrade

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
private Trade getTrade() {
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpGet request = new HttpGet(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/openTrades");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	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);
		try {
			 JSONObject trade = resultJson.getJSONArray("trades").getJSONObject(0);
			 //System.out.println(trade);
			 Trade t = new Trade();
			 t.setId(trade.getLong("id"));
			 t.setOpeningPrice(trade.getDouble("price"));
			 t.setBuyOrSell(trade.getString("currentUnits").contains("-") ? "sell" : "buy");
			 return t;
		}
		catch (JSONException je) {
			return null;
		}
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
	
}
 
开发者ID:toni8810,项目名称:TradingRobot,代码行数:36,代码来源:Trading.java

示例14: getHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
/**
 * @see http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
 * @return
 * @throws Exception
 */
public static synchronized HttpClient getHttpClient() 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 = ;

   // now, we create connection-manager using our Registry.
   //      -- allows multi-threaded use
   PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build());
   b.setConnectionManager(connMgr);

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

   return client;
}
 
开发者ID:wellsb1,项目名称:fort_w,代码行数:43,代码来源:Web.java

示例15: HttpClientConfigurer

import org.apache.http.impl.client.HttpClientBuilder; //导入方法依赖的package包/类
protected HttpClientConfigurer() {
	httpClientBuilder = HttpClientBuilder.create();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-skipper,代码行数:4,代码来源:HttpClientConfigurer.java


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