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

The following are Jave code examples for showing how to use create() 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: Java-APIs   File: OEModelEndpoint.java   Source Code and License Vote up 7 votes
/**
 * @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;
}
 
Example 2
Project: groupsio-api-java   File: BaseResource.java   Source Code and License Vote up 6 votes
/**
 * 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();
}
 
Example 3
Project: minsx-java-example   File: RemoteServerClientImpl.java   Source Code and License Vote up 6 votes
@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();
}
 
Example 4
Project: TradingRobot   File: Account.java   Source Code and License Vote up 6 votes
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;
}
 
Example 5
Project: bubble2   File: HttpUtils.java   Source Code and License Vote up 6 votes
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();
	}
}
 
Example 6
Project: Cognizant-Intelligent-Test-Scripter   File: RemoteProxy.java   Source Code and License Vote up 6 votes
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);

    }
 
Example 7
Project: Reer   File: HttpClientHelper.java   Source Code and License Vote up 5 votes
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;
}
 
Example 8
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License Vote up 5 votes
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()));
	}
 
Example 9
Project: ts-benchmark   File: HttpTest.java   Source Code and License Vote up 5 votes
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;
}
 
Example 10
Project: TradingRobot   File: Trading.java   Source Code and License Vote up 5 votes
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;
	}
	
}
 
Example 11
Project: Java-APIs   File: OEModelEndpoint.java   Source Code and License Vote up 5 votes
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");
  }
}
 
Example 12
Project: TradingRobot   File: Trading.java   Source Code and License Vote up 5 votes
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;
	}
	
}
 
Example 13
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License Vote up 5 votes
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()));
	}
 
Example 14
Project: fort_w   File: Web.java   Source Code and License Vote up 5 votes
/**
 * @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;
}
 
Example 15
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License Vote up 5 votes
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()));
	}
 
Example 16
Project: spring-cloud-skipper   File: HttpClientConfigurer.java   Source Code and License Vote up 4 votes
protected HttpClientConfigurer() {
	httpClientBuilder = HttpClientBuilder.create();
}
 
Example 17
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());
}
 
Example 18
Project: sling-org-apache-sling-testing-clients   File: SlingClient.java   Source Code and License Vote up 4 votes
protected InternalBuilder(URI url, String user, String password) {
    this.httpClientBuilder = HttpClientBuilder.create();
    this.configBuilder = SlingClientConfig.Builder.create().setUrl(url).setUser(user).setPassword(password);

    setDefaults();
}
 
Example 19
Project: QuickHttp   File: QuickHttpController.java   Source Code and License Vote up 4 votes
private CloseableHttpClient createHttpClient(){
    HttpClientBuilder builder =  HttpClientBuilder.create();
    return builder.build();
}
 
Example 20
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;
}