本文整理汇总了Java中org.apache.http.impl.client.HttpClientBuilder类的典型用法代码示例。如果您正苦于以下问题:Java HttpClientBuilder类的具体用法?Java HttpClientBuilder怎么用?Java HttpClientBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpClientBuilder类属于org.apache.http.impl.client包,在下文中一共展示了HttpClientBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: register
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private void register(RegisterModel model) throws Exception {
String url = "http://" + properties.getScouter().getHost() + ":" + properties.getScouter().getPort() + "/register";
String param = new Gson().toJson(model);
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type","application/json");
post.setEntity(new StringEntity(param));
CloseableHttpClient client = HttpClientBuilder.create().build();
// send the post request
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
logger.info("Register message sent to [{}] for [{}].", url, model.getObject().getDisplay());
} else {
logger.warn("Register message sent failed. Verify below information.");
logger.warn("[URL] : " + url);
logger.warn("[Message] : " + param);
logger.warn("[Reason] : " + EntityUtils.toString(response.getEntity(), "UTF-8"));
}
}
示例2: ensureApiCalled
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private void ensureApiCalled() {
if (!this.available) {
return;
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(RELEASE_COVERS_ENDPOINT + releaseId);
getRequest.addHeader("accept", "application/json");
try {
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
this.available = false;
return;
}
this.coverArtResponse = mapper.readValue(response.getEntity().getContent(), CoverArtArchiveResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
}
示例3: sendSlackImageResponse
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private void sendSlackImageResponse(ObjectNode json, String s3Key) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode message = mapper.createObjectNode();
ArrayNode attachments = mapper.createArrayNode();
ObjectNode attachment = mapper.createObjectNode();
String emoji = json.get("text").asText();
if (UrlValidator.getInstance().isValid(emoji)) {
attachment.put("title_link", emoji);
emoji = StringUtils.substringAfterLast(emoji, "/");
}
String username = json.get("user_name").asText();
String responseUrl = json.get("response_url").asText();
String slackChannelId = json.get("channel_id").asText();
String imageUrl = String.format("https://s3.amazonaws.com/%s/%s", PROPERTIES.getProperty(S3_BUCKET_NAME), s3Key);
message.put("response_type", "in_channel");
message.put("channel_id", slackChannelId);
attachment.put("title", resolveMessage("slackImageResponse", emoji, username));
attachment.put("fallback", resolveMessage("approximated", emoji));
attachment.put("image_url", imageUrl);
attachments.add(attachment);
message.set("attachments", attachments);
HttpClient client = HttpClientBuilder.create().build();
HttpPost slackResponseReq = new HttpPost(responseUrl);
slackResponseReq.setEntity(new StringEntity(mapper.writeValueAsString(message), ContentType.APPLICATION_JSON));
HttpResponse slackResponse = client.execute(slackResponseReq);
int status = slackResponse.getStatusLine().getStatusCode();
LOG.info("Got {} status from Slack API after sending approximation to response url.", status);
} catch (UnsupportedOperationException | IOException e) {
LOG.error("Exception occured when sending Slack response", e);
}
}
示例4: setupSSL
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
/**
* Setup SSL. Pass the trusted certificates and client private key and certificate,
* if applicable.
*
* @param httpClientBuilder The client builder
* @throws HttpException
*/
private void setupSSL( HttpClientBuilder httpClientBuilder ) throws HttpException {
try {
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
// set trust material
if (trustedServerCertificates != null && trustedServerCertificates.length > 0) {
sslContextBuilder.loadTrustMaterial(convertToKeyStore(trustedServerCertificates),
new TrustStrategy() {
@Override
public boolean isTrusted( X509Certificate[] chain,
String authType ) throws CertificateException {
return checkIsTrusted(chain);
}
});
} else {
// no trust material provided, we will trust no matter the remote party
sslContextBuilder.loadTrustMaterial(
new TrustStrategy() {
@Override
public boolean
示例5: testHttpRequestGet
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
@Test
public void testHttpRequestGet() throws Exception {
RequestConfig.Builder req = RequestConfig.custom();
req.setConnectTimeout(5000);
req.setConnectionRequestTimeout(5000);
req.setRedirectsEnabled(false);
req.setSocketTimeout(5000);
req.setExpectContinueEnabled(false);
HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
get.setConfig(req.build());
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(5);
HttpClientBuilder builder = HttpClients.custom();
builder.disableAutomaticRetries();
builder.disableRedirectHandling();
builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
builder.setConnectionManager(cm);
CloseableHttpClient client = builder.build();
String s = client.execute(get, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
assertEquals(301, response.getStatusLine().getStatusCode());
return "success";
}
});
assertEquals("success", s);
}
示例6: testRetryAsync3
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
@Ignore
public void testRetryAsync3() throws Exception {
final int TIME_OUT = 30000;
ThreadPoolExecutor executor = RetryUtil.createThreadPoolExecutor();
String res = RetryUtil.asyncExecuteWithRetry(new Callable<String>() {
@Override
public String call() throws Exception {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT)
.setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT)
.setStaleConnectionCheckEnabled(true).build();
HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(10).setMaxConnPerRoute(10)
.setDefaultRequestConfig(requestConfig).build();
HttpGet httpGet = new HttpGet();
httpGet.setURI(new URI("http://0.0.0.0:8080/test"));
httpClient.execute(httpGet);
return OK;
}
}, 3, 1000L, false, 6000L, executor);
Assert.assertEquals(res, OK);
// Assert.assertEquals(RetryUtil.EXECUTOR.getActiveCount(), 0);
}
示例7: RocketChatEndpoint
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
public RocketChatEndpoint(
@Value("${rocketchat.proxy.hostname:}") String proxyHostname,
@Value("${rocketchat.proxy.port:80}") int proxyPort,
@Value("${rocketchat.proxy.scheme:http}") String proxyScheme
) {
httpClientBuilder = HttpClientBuilder.create()
.setRetryHandler((exception, executionCount, context) -> executionCount < 3)
.setConnectionBackoffStrategy(new ConnectionBackoffStrategy() {
@Override
public boolean shouldBackoff(Throwable t) {
return t instanceof IOException;
}
@Override
public boolean shouldBackoff(HttpResponse resp) {
return false;
}
})
.setUserAgent("Smarti/0.0 Rocket.Chat-Endpoint/0.1");
if(StringUtils.isNotBlank(proxyHostname)) {
httpClientBuilder.setProxy(new HttpHost(proxyHostname, proxyPort, proxyScheme));
}
}
示例8: getEntity
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private String getEntity(URI url) throws IOException {
final HttpGet get = new HttpGet(url);
get.setConfig(requestConfig);
get.setHeader("Accept", "application/json");
HttpClientBuilder clientBuilder = HttpClients.custom();
if (sslContext != null) {
clientBuilder.setSslcontext(sslContext);
}
try (CloseableHttpClient httpClient = clientBuilder.build()) {
try (CloseableHttpResponse response = httpClient.execute(get)) {
final StatusLine statusLine = response.getStatusLine();
final int statusCode = statusLine.getStatusCode();
if (200 != statusCode) {
final String msg = String.format("Failed to get entity from %s, response=%d:%s",
get.getURI(), statusCode, statusLine.getReasonPhrase());
throw new RuntimeException(msg);
}
final HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
}
}
示例9: getUser
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private User getUser(@NotNull Token token) throws IOException, URISyntaxException {
URIBuilder builder = new URIBuilder(PROFILE_URL);
builder.addParameter("access_token", token.getAccessToken());
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(builder.build());
org.apache.http.HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
InputStream inputStream = response.getEntity().getContent();
if (HttpUtilities.success(statusCode)) {
User user = gson.fromJson(new InputStreamReader(inputStream), User.class);
user.setToken(token);
return user;
}
throw new ApiException(HttpStatus.valueOf(statusCode));
}
示例10: 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();
}
}
示例11: getAccessToken
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private Token getAccessToken(@NotNull String code) throws IOException {
// Initialize client
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(TOKEN_URL);
// add request parameters
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("code", code));
parameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
parameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
parameters.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
parameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
// send request
org.apache.http.HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
InputStream inputStream = response.getEntity().getContent();
if (HttpUtilities.success(statusCode))
return gson.fromJson(new InputStreamReader(inputStream), Token.class);
throw new ApiException(HttpStatus.valueOf(statusCode));
}
示例12: sendSlackTextResponse
import org.apache.http.impl.client.HttpClientBuilder; //导入依赖的package包/类
private void sendSlackTextResponse(ObjectNode json, String message) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode messageNode = mapper.createObjectNode();
String responseUrl = json.get("response_url").asText();
String slackChannelId = json.get("channel_id").asText();
messageNode.put("text", message);
messageNode.put("channel_id", slackChannelId);
HttpClient client = HttpClientBuilder.create().build();
HttpPost slackResponseReq = new HttpPost(responseUrl);
slackResponseReq.setEntity(new StringEntity(mapper.writeValueAsString(messageNode), ContentType.APPLICATION_JSON));
HttpResponse slackResponse = client.execute(slackResponseReq);
int status = slackResponse.getStatusLine().getStatusCode();
LOG.info("Got {} status from Slack API after sending request to response url.", status);
} catch (UnsupportedOperationException | IOException e) {
LOG.error("Exception occured when sending Slack response", e);
}
}
示例13: 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();
}
}
}
示例14: 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");
}
示例15: 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();
}