本文整理汇总了Java中org.apache.http.impl.client.CloseableHttpClient类的典型用法代码示例。如果您正苦于以下问题:Java CloseableHttpClient类的具体用法?Java CloseableHttpClient怎么用?Java CloseableHttpClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CloseableHttpClient类属于org.apache.http.impl.client包,在下文中一共展示了CloseableHttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: client
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
@Test
public void client() throws URISyntaxException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
CloseableHttpResponse response = httpclient.execute(httpget);
}
示例2: getRedirect
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
/**
* get a redirect for an url: this method shall be called if it is expected that a url
* is redirected to another url. This method then discovers the redirect.
* @param urlstring
* @param useAuthentication
* @return the redirect url for the given urlstring
* @throws IOException if the url is not redirected
*/
public static String getRedirect(String urlstring) throws IOException {
HttpGet get = new HttpGet(urlstring);
get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
CloseableHttpClient httpClient = getClosableHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
if (httpResponse.getStatusLine().getStatusCode() == 301) {
for (Header header: httpResponse.getAllHeaders()) {
if (header.getName().equalsIgnoreCase("location")) {
EntityUtils.consumeQuietly(httpEntity);
return header.getValue();
}
}
EntityUtils.consumeQuietly(httpEntity);
throw new IOException("redirect for " + urlstring+ ": no location attribute found");
} else {
EntityUtils.consumeQuietly(httpEntity);
throw new IOException("no redirect for " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
}
} else {
throw new IOException("client connection to " + urlstring + " fail: no connection");
}
}
示例3: login
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
public static String login(String randCode) {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.loginUrl);
httpPost.addHeader(CookieManager.cookieHeader());
String param = "username=" + encode(UserConfig.username) + "&password=" + encode(UserConfig.password) + "&appid=otn";
httpPost.setEntity(new StringEntity(param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
result = EntityUtils.toString(response.getEntity());
CookieManager.touch(response);
ResultManager.touch(result, new ResultKey("uamtk", "uamtk"));
} catch (IOException e) {
logger.error("login error", e);
}
return result;
}
示例4: checkOrderInfo
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
public static String checkOrderInfo(TrainQuery query) {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo);
httpPost.addHeader(CookieManager.cookieHeader());
httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
CookieManager.touch(response);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.error("checkUser error", e);
}
return result;
}
示例5: captchaImage
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
private static byte[] captchaImage(String url) {
Objects.requireNonNull(url);
CloseableHttpClient httpClient = buildHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(CookieManager.cookieHeader());
byte[] result = new byte[0];
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
CookieManager.touch(response);
result = EntityUtils.toByteArray(response.getEntity());
} catch (IOException e) {
logger.error("captchaImage error", e);
}
return result;
}
示例6: load
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
@Override
public List<User> load() {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();) {
ArrayList<User> users = new ArrayList<>();
String url = protocol+"://" + hostAndPort + "/openidm/managed/user?_prettyPrint=true&_queryId=query-all";
HttpGet request = new HttpGet(url);
configure(request);
try (CloseableHttpResponse response = httpClient.execute(request);) {
String result = EntityUtils.toString(response.getEntity());
logger.trace(result);
// parse the json result and find the largest id
JSONObject obj = new JSONObject(result);
JSONArray arr = obj.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
String usernameFromId = arr.getJSONObject(i).getString("_id");
String email = arr.getJSONObject(i).getString("mail");
String username = arr.getJSONObject(i).getString("userName");
String firstname = arr.getJSONObject(i).getString("givenName");
String lastname = arr.getJSONObject(i).getString("sn");
User user = new User(username, email, firstname, lastname);
users.add(user);
if (!user.idFromUsenameForForgeRock().equals(usernameFromId)) {
logger.warn(
"We modeled a single field for both id and username and the server has two different values ["
+ usernameFromId + "] != [" + username
+ "]. The first value will be used for both.");
}
}
}
return users;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
示例7: simpleGet
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
/**
* Simple Http Get.
*
* @param path the path
* @return the CloseableHttpResponse
* @throws URISyntaxException the URI syntax exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws MininetException the MininetException
*/
public CloseableHttpResponse simpleGet(String path)
throws URISyntaxException, IOException, MininetException {
URI uri = new URIBuilder()
.setScheme("http")
.setHost(mininetServerIP.toString())
.setPort(mininetServerPort.getPort())
.setPath(path)
.build();
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig config = RequestConfig
.custom()
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();
HttpGet request = new HttpGet(uri);
request.setConfig(config);
request.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 300) {
throw new MininetException(String.format("failure - received a %d for %s.",
response.getStatusLine().getStatusCode(), request.getURI().toString()));
}
return response;
}
示例8: sendDelete
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
public DockerResponse sendDelete(URI uri, Boolean httpRequired) throws JSONClientException {
if (logger.isDebugEnabled()) {
logger.debug("Send a delete request to : " + uri);
}
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpClient = buildSecureHttpClient();
HttpDelete httpDelete = new HttpDelete(uri);
response = httpClient.execute(httpDelete);
} catch (IOException e) {
throw new JSONClientException("Error in sendDelete method due to : " + e.getMessage(), e);
}
if (logger.isDebugEnabled()) {
logger.debug("Status code : " + response.getStatusLine().getStatusCode());
}
return new DockerResponse(response.getStatusLine().getStatusCode(), "");
}
示例9: ResponseWrap
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context,
ObjectMapper _mapper) {
this.response = response;
this.httpClient = httpClient;
this.request = request;
this.context = context;
mapper = _mapper;
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
this.entity = new BufferedHttpEntity(entity);
} else {
this.entity = new BasicHttpEntity();
}
EntityUtils.consumeQuietly(entity);
this.response.close();
} catch (IOException e) {
logger.warn(e.getMessage());
}
}
示例10: main
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
public static void main(String[] args) throws IOException, URISyntaxException {
ObjectMapper mapper = new ObjectMapper();
try (CloseableHttpClient client =
HttpClientBuilder.create().useSystemProperties().build()) {
URI uri = new URIBuilder("http://api.geonames.org/searchJSON")
.addParameter("q", "kabupaten garut")
.addParameter("username", "ceefour")
.build();
HttpGet getRequest = new HttpGet(uri);
try (CloseableHttpResponse resp = client.execute(getRequest)) {
String body = IOUtils.toString(resp.getEntity().getContent(),
StandardCharsets.UTF_8);
JsonNode bodyNode = mapper.readTree(body);
LOG.info("Status: {}", resp.getStatusLine());
LOG.info("Headers: {}", resp.getAllHeaders());
LOG.info("Body: {}", body);
LOG.info("Body (JsonNode): {}", bodyNode);
for (JsonNode child : bodyNode.get("geonames")) {
LOG.info("Place: {} ({}, {})", child.get("toponymName"), child.get("lat"), child.get("lng"));
}
}
}
}
示例11: post
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
/**
* httpClient post 获取资源
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, Object> params) {
log.info(url);
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
Object object = params.get(key);
nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e);
}
return null;
}
示例12: constructHttpClient
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
protected CloseableHttpClient constructHttpClient() throws IOException {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(20 * 1000)
.setConnectionRequestTimeout(20 * 1000)
.setSocketTimeout(20 * 1000)
.setMaxRedirects(20)
.build();
URL mmsc = new URL(apn.getMmsc());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if (apn.hasAuthentication()) {
credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
}
return HttpClients.custom()
.setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
.setRedirectStrategy(new LaxRedirectStrategy())
.setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
.setConnectionManager(new BasicHttpClientConnectionManager())
.setDefaultRequestConfig(config)
.setDefaultCredentialsProvider(credsProvider)
.build();
}
示例13: query
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
private <REQ, RESP> RESP query(REQ request, Class<RESP> clazz) throws IOException, DruidException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(configuration.getUrl());
StringEntity entity = new StringEntity(mapper.writeValueAsString(request), configuration.getCharset());
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
String content = EntityUtils.toString(response.getEntity(), configuration.getCharset());
try {
return mapper.readValue(content, clazz);
} catch (Exception ex) {
throw new DruidException(content);
} finally {
client.close();
}
}
示例14: getAttemptId
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
private static int getAttemptId(@NotNull Task task) throws IOException {
final StepicWrappers.AdaptiveAttemptWrapper attemptWrapper = new StepicWrappers.AdaptiveAttemptWrapper(task.getStepId());
final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.ATTEMPTS);
post.setEntity(new StringEntity(new Gson().toJson(attemptWrapper)));
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return -1;
setTimeout(post);
final CloseableHttpResponse httpResponse = client.execute(post);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
final HttpEntity entity = httpResponse.getEntity();
final String entityString = EntityUtils.toString(entity);
EntityUtils.consume(entity);
if (statusCode == HttpStatus.SC_CREATED) {
final StepicWrappers.AttemptContainer container =
new Gson().fromJson(entityString, StepicWrappers.AttemptContainer.class);
return (container.attempts != null && !container.attempts.isEmpty()) ? container.attempts.get(0).id : -1;
}
return -1;
}
示例15: execute
import org.apache.http.impl.client.CloseableHttpClient; //导入依赖的package包/类
public <T> Response<T> execute() {
HttpProxy httpProxy = getHttpProxyFromPool();
CookieStore cookieStore = getCookieStoreFromPool();
CloseableHttpClient httpClient = httpClientPool.getHttpClient(siteConfig, request);
HttpUriRequest httpRequest = httpClientPool.createHttpUriRequest(siteConfig, request, createHttpHost(httpProxy));
CloseableHttpResponse httpResponse = null;
IOException executeException = null;
try {
HttpContext httpContext = createHttpContext(httpProxy, cookieStore);
httpResponse = httpClient.execute(httpRequest, httpContext);
} catch (IOException e) {
executeException = e;
}
Response<T> response = ResponseFactory.createResponse(
request.getResponseType(), siteConfig.getCharset(request.getUrl()));
response.handleHttpResponse(httpResponse, executeException);
return response;
}