下面列出了怎么用org.apache.http.client.utils.HttpClientUtils的API类实例代码及写法,或者点击链接到github查看源代码。
public static String get(String url) {
if (StringUtils.isBlank(url)) {
return null;
}
String result = null;
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build());
response = httpclient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
LOGGER.warn("请求" + url + "异常", e);
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpclient);
}
return result;
}
@Override
public void completed(HttpResponse httpResponse) {
try {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
String response = EntityUtils.toString(httpResponse.getEntity());
// logger.info(response);
synchronized (object) {
result.add(response);
}
}
} catch (IOException e){
logger.info("network io exception",e);
} finally {
latch.countDown();
HttpClientUtils.closeQuietly(httpResponse);
}
}
public static String sendRecordingRequest(final String url) {
CloseableHttpResponse response = null;
try (final CloseableHttpClient client = HttpClientBuilder.create().build()) {
final HttpGet get = new HttpGet(url);
response = client.execute(get);
HttpEntity content = response.getEntity();
String message = EntityUtils.toString(content);
LOGGER.info("Response: " + message);
return message;
} catch (Exception ex) {
LOGGER.severe("Request: " + ex);
} finally {
HttpClientUtils.closeQuietly(response);
}
return "";
}
public static String sendRecordingRequest(final String url) {
CloseableHttpResponse response = null;
try (final CloseableHttpClient client = HttpClientBuilder.create().build()) {
final HttpGet get = new HttpGet(url);
response = client.execute(get);
HttpEntity content = response.getEntity();
String message = EntityUtils.toString(content);
LOGGER.info("Response: " + message);
return message;
} catch (Exception ex) {
LOGGER.severe("Request: " + ex);
} finally {
HttpClientUtils.closeQuietly(response);
}
return "";
}
/**
* This method executes the given {@link ApacheCloudStackRequest}.
* It will return the response as a plain {@link String}.
* You should have in mind that if the parameter 'response' is not set, the default is 'XML'.
*/
public String executeRequest(ApacheCloudStackRequest request) {
boolean isSecretKeyApiKeyAuthenticationMechanism = StringUtils.isNotBlank(this.apacheCloudStackUser.getApiKey());
String urlRequest = createApacheCloudStackApiUrlRequest(request, isSecretKeyApiKeyAuthenticationMechanism);
LOGGER.debug(String.format("Executing request[%s].", urlRequest));
CloseableHttpClient httpClient = createHttpClient();
HttpContext httpContext = createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(httpClient, isSecretKeyApiKeyAuthenticationMechanism);
try {
return executeRequestGetResponseAsString(urlRequest, httpClient, httpContext);
} finally {
if (!isSecretKeyApiKeyAuthenticationMechanism) {
executeUserLogout(httpClient, httpContext);
}
HttpClientUtils.closeQuietly(httpClient);
}
}
public FluxRuntimeConnectorHttpImpl(Long connectionTimeout, Long socketTimeout, String fluxEndpoint, ObjectMapper objectMapper,
MetricRegistry metricRegistry) {
this.fluxEndpoint = fluxEndpoint;
this.objectMapper = objectMapper;
RequestConfig clientConfig = RequestConfig.custom()
.setConnectTimeout((connectionTimeout).intValue())
.setSocketTimeout((socketTimeout).intValue())
.setConnectionRequestTimeout((socketTimeout).intValue())
.build();
PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
syncConnectionManager.setMaxTotal(MAX_TOTAL);
syncConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager)
.build();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
HttpClientUtils.closeQuietly(closeableHttpClient);
}));
this.metricRegistry = metricRegistry;
}
@Override
public void submitNewWorkflow(StateMachineDefinition stateMachineDef) {
CloseableHttpResponse httpResponse = null;
try {
httpResponse = postOverHttp(stateMachineDef, "");
if(logger.isDebugEnabled()) {
try {
logger.debug("Flux returned response: {}", EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
@Override
public void submitEvent(String name, Object data, String correlationId, String eventSource) {
final String eventType = data.getClass().getName();
if (eventSource == null) {
eventSource = EXTERNAL;
}
CloseableHttpResponse httpResponse = null;
try {
final EventData eventData = new EventData(name, eventType, objectMapper.writeValueAsString(data), eventSource);
httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
@Override
public void submitEventUpdate(String name, Object data, String correlationId,String eventSource) {
final String eventType = data.getClass().getName();
if (eventSource == null) {
eventSource = EXTERNAL;
}
CloseableHttpResponse httpResponse = null;
try {
final EventData eventData = new EventData(name, eventType, objectMapper.writeValueAsString(data), eventSource);
httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/eventupdate");
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
@Override
public void submitEvent(String name, Object data, String correlationId, String eventSource) {
final String eventType = data.getClass().getName();
if (eventSource == null) {
eventSource = EXTERNAL;
}
CloseableHttpResponse httpResponse = null;
try {
final EventData eventData = new EventData(name, eventType, (String) data, eventSource);
httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
@Override
public void submitScheduledEvent(String name, Object data, String correlationId,String eventSource, Long triggerTime) {
final String eventType = data.getClass().getName();
if (eventSource == null) {
eventSource = EXTERNAL;
}
final EventData eventData = new EventData(name, eventType, (String) data, eventSource);
CloseableHttpResponse httpResponse = null;
try {
if(triggerTime != null) {
httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId&triggerTime=" + triggerTime);
} else {
//this block is used by flux to trigger the event when the time has arrived, send the data as plain string without serializing,
// as the data is already in serialized form (in ScheduledEvents table the data stored in serialized form)
httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
@Inject
public ExecutionNodeTaskDispatcherImpl(@Named("connector.max.connections") Integer maxConnections, @Named("connector.max.connections.per.route") Integer maxConnectionsPerRoute,
@Named("connector.connection.timeout") Integer connectionTimeout, @Named("connector.socket.timeout") Integer socketTimeOut,
MetricsClient metricsClient) {
RequestConfig clientConfig = RequestConfig.custom()
.setConnectTimeout((connectionTimeout).intValue())
.setSocketTimeout((socketTimeOut).intValue())
.setConnectionRequestTimeout((socketTimeOut).intValue())
.build();
PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
syncConnectionManager.setMaxTotal(maxConnections);
syncConnectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager)
.build();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
HttpClientUtils.closeQuietly(closeableHttpClient);
}));
this.metricsClient = metricsClient;
}
@Test
public void contentTypeDetectedFromContent() throws Exception {
HttpEntity textEntity = new StringEntity("test");
rawClient.put("path/to/content", textEntity);
HttpResponse response = rawClient.get("path/to/content");
MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_PLAIN));
HttpClientUtils.closeQuietly(response);
HttpEntity htmlEntity = new StringEntity("<html>...</html>");
rawClient.put("path/to/content", htmlEntity);
response = rawClient.get("path/to/content");
MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_HTML));
HttpClientUtils.closeQuietly(response);
// turn off strict validation so we can test falling back to declared content-type
Configuration hostedConfig = repositoryManager.get(HOSTED_REPO).getConfiguration().copy();
hostedConfig.attributes(STORAGE).set(STRICT_CONTENT_TYPE_VALIDATION, false);
repositoryManager.update(hostedConfig);
HttpEntity jsonEntity = new StringEntity("", ContentType.APPLICATION_JSON);
rawClient.put("path/to/content", jsonEntity);
response = rawClient.get("path/to/content");
MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.APPLICATION_JSON));
HttpClientUtils.closeQuietly(response);
}
static boolean isResponseContentValid(String url) {
if ("true".equals(System.getProperty("bash.skipUrls", "false"))) {
return true;
}
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
CloseableHttpResponse response = httpClient.execute(new HttpOptions(url));
Assert.assertTrue("Expected response content for " + url, 404 != response.getStatusLine().getStatusCode());
String content = EntityUtils.toString(response.getEntity());
return !content.contains("No matches for");
} catch (Exception e) {
return false;
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
/**
* Calling close will force the method to close, and will
* force any open stream to terminate. If the session is local,
* Then that too will be closed.
*/
public synchronized void close() {
if (closed)
return; // recursive calls ok
closed = true; // mark as closed to prevent recursive calls
if (methodstream != null) {
try {
this.methodstream.close(); // May recursr
} catch (IOException ioe) {
/* failure is ok */}
this.methodstream = null;
}
// Force release underlying connection back to the connection manager
if (this.lastresponse != null) {
if (false) {
try {
try {
// Attempt to keep connection alive by consuming its remaining content
EntityUtils.consume(this.lastresponse.getEntity());
} finally {
HttpClientUtils.closeQuietly(this.lastresponse); // Paranoia
}
} catch (IOException ignore) {
/* ignore */}
} else
HttpClientUtils.closeQuietly(this.lastresponse);
this.lastresponse = null;
}
if (session != null) {
session.removeMethod(this);
if (localsession) {
session.close();
session = null;
}
}
this.lastrequest = null;
}
public boolean sendMessage(String message) {
boolean ret = false;
if(httpClient == null) {
initialize();
}
HttpPost httpPost = new HttpPost(baseUrl);
CloseableHttpResponse response = null;
try {
for(String chatId: chatIds) {
JSONObject params = new JSONObject();
params.put("chat_id", chatId);
params.put("text", message);
params.put("parse_mode", "HTML");
httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));
response = httpClient.execute(httpPost);
log.debug("telegram-send-message-response-code: " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
ret = true;
}
}
} catch (IOException e) {
log.error(e.getMessage());
} finally {
HttpClientUtils.closeQuietly(response);
}
return ret;
}
public boolean sendMessage(String inToken, String chatId, String message) {
boolean ret = false;
baseUrl = "https://api.telegram.org/bot" + inToken + "/sendMessage";
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();
HttpPost httpPost = new HttpPost(baseUrl);
CloseableHttpResponse response = null;
log.debug("token:" + inToken);
log.debug("chatId: " + chatId);
try {
JSONObject params = new JSONObject();
params.put("chat_id", chatId);
params.put("text", message);
params.put("parse_mode", "HTML");
httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));
response = httpClient.execute(httpPost);
log.debug("telegram-send-message-response-code: " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
ret = true;
}
} catch (IOException e) {
log.error(e.getMessage());
} finally {
HttpClientUtils.closeQuietly(response);
}
return ret;
}
public String getPoster(String query) {
// log.debug("Get Poster: " + query);
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(this.baseUrl);
builder.setParameter("id", "movie").setParameter("multiple", "0").setParameter("mod", "json")
.setParameter("code", "utf_in_out").setParameter("limit", String.valueOf(limit))
.setParameter("q", query);
HttpGet httpGet = new HttpGet(builder.build());
response = httpClient.execute(httpGet);
JSONObject json = new JSONObject(EntityUtils.toString(response.getEntity()));
// log.debug(json.toString());
if(json.has("items")) {
JSONArray jarr = json.getJSONArray("items");
for(int i = 0; i < jarr.length(); i++) {
String[] arr = StringUtils.split(jarr.getString(i), "|");
if(arr.length > 2) {
if(StringUtils.containsIgnoreCase(arr[0], query)) {
return arr[2];
}
}
}
}
} catch (URISyntaxException | IOException | ParseException | JSONException e) {
log.error(e.getMessage());
} finally {
HttpClientUtils.closeQuietly(response);
}
return null;
}
/**
* 统一处理请求
*
* @param request 请求对象
* @return 响应字符串
*/
private static String handlerRequest(HttpUriRequest request) {
try {
CloseableHttpResponse response = HTTP_CLIENT.execute(request);
String body = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Messages.showWarningDialog("连接到服务器错误!", MsgValue.TITLE_INFO);
return null;
}
HttpClientUtils.closeQuietly(response);
// 解析JSON数据
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(body);
if (jsonNode.get(STATE_CODE).asInt() == 0) {
JsonNode data = jsonNode.get("data");
if (data instanceof TextNode) {
return data.asText();
}
return data.toString();
}
// 获取错误消息
String msg = jsonNode.get("msg").asText();
Messages.showWarningDialog(msg, MsgValue.TITLE_INFO);
} catch (IOException e) {
Messages.showWarningDialog("无法连接到服务器!", MsgValue.TITLE_INFO);
ExceptionUtil.rethrow(e);
}
return null;
}
/**
* @param httpClient The httpClient to use for remote/service calls.
*/
@Override
public void setHttpClient(HttpClient httpClient) {
synchronized (this) {
this.httpClient = Objects.requireNonNull(httpClient, "HTTP Client cannot be null");
// If they set a client, we need to check whether we need to
// close any existing dependentClient
CloseableHttpClient toCloseDependentClient = dependentClient;
dependentClient = null;
if (toCloseDependentClient != null) {
HttpClientUtils.closeQuietly(toCloseDependentClient);
}
}
}
@Override
public void submitEventAndUpdateStatus(EventData eventData, String stateMachineId, ExecutionUpdateData executionUpdateData) {
CloseableHttpResponse httpResponse = null;
try {
EventAndExecutionData eventAndExecutionData = new EventAndExecutionData(eventData, executionUpdateData);
httpResponse = postOverHttp(eventAndExecutionData, "/" + stateMachineId + "/context/eventandstatus");
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
@Override
public void cancelEvent(String eventName, String correlationId) {
CloseableHttpResponse httpResponse = null;
try {
final EventData eventData = new EventData(eventName, null, null, null, true);
httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
/**
* Interface method implementation. Increments the execution retries in persistence by invoking suitable Flux runtime API
* @see com.flipkart.flux.client.runtime.FluxRuntimeConnector#incrementExecutionRetries(String, Long)
*/
@Override
public void incrementExecutionRetries(String stateMachineId, Long taskId) {
CloseableHttpResponse httpResponse = null;
httpResponse = postOverHttp(null, "/" + stateMachineId + "/" + taskId + "/retries/inc");
HttpClientUtils.closeQuietly(httpResponse);
}
/**
* Interface method implementation. Posts to Flux Runtime API to redrive a task.
*/
@Override
public void redriveTask(String stateMachineId, Long taskId) {
CloseableHttpResponse httpResponse = null;
httpResponse = postOverHttp(null, "/redrivetask/" + stateMachineId + "/taskId/"+ taskId);
HttpClientUtils.closeQuietly(httpResponse);
}
private Optional<SnapshotItem> fetchLatest(ContentSpecifier spec) throws IOException {
AptFacet aptFacet = getRepository().facet(AptFacet.class);
ProxyFacet proxyFacet = facet(ProxyFacet.class);
HttpClientFacet httpClientFacet = facet(HttpClientFacet.class);
HttpClient httpClient = httpClientFacet.getHttpClient();
CacheController cacheController = cacheControllerHolder.getMetadataCacheController();
CacheInfo cacheInfo = cacheController.current();
Content oldVersion = aptFacet.get(spec.path);
URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path);
HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri);
HttpResponse response = httpClient.execute(getRequest);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
Content fetchedContent = new Content(new HttpEntityPayload(response, entity));
AttributesMap contentAttrs = fetchedContent.getAttributes();
contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED));
contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG));
contentAttrs.set(CacheInfo.class, cacheInfo);
Content storedContent = getAptFacet().put(spec.path, fetchedContent);
return Optional.of(new SnapshotItem(spec, storedContent));
}
try {
if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri);
doIndicateVerified(oldVersion, cacheInfo, spec.path);
return Optional.of(new SnapshotItem(spec, oldVersion));
}
throwProxyExceptionForStatus(response);
}
finally {
HttpClientUtils.closeQuietly(response);
}
return Optional.empty();
}
@Test
public void contentTypeDetectedFromPath() throws Exception {
HttpEntity testEntity = new ByteArrayEntity(new byte[0]);
rawClient.put("path/to/content.txt", testEntity);
HttpResponse response = rawClient.get("path/to/content.txt");
MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_PLAIN));
HttpClientUtils.closeQuietly(response);
rawClient.put("path/to/content.html", testEntity);
response = rawClient.get("path/to/content.html");
MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_HTML));
HttpClientUtils.closeQuietly(response);
}
private Optional<SnapshotItem> fetchLatest(final ContentSpecifier spec) throws IOException {
AptFacet aptFacet = getRepository().facet(AptFacet.class);
ProxyFacet proxyFacet = facet(ProxyFacet.class);
HttpClientFacet httpClientFacet = facet(HttpClientFacet.class);
HttpClient httpClient = httpClientFacet.getHttpClient();
CacheController cacheController = cacheControllerHolder.getMetadataCacheController();
CacheInfo cacheInfo = cacheController.current();
Content oldVersion = aptFacet.get(spec.path);
URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path);
HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri);
HttpResponse response = httpClient.execute(getRequest);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
Content fetchedContent = new Content(new HttpEntityPayload(response, entity));
AttributesMap contentAttrs = fetchedContent.getAttributes();
contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED));
contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG));
contentAttrs.set(CacheInfo.class, cacheInfo);
Content storedContent = getAptFacet().put(spec.path, fetchedContent);
return Optional.of(new SnapshotItem(spec, storedContent));
}
try {
if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri);
doIndicateVerified(oldVersion, cacheInfo, spec.path);
return Optional.of(new SnapshotItem(spec, oldVersion));
}
throwProxyExceptionForStatus(response);
}
finally {
HttpClientUtils.closeQuietly(response);
}
return Optional.empty();
}
private void mayThrowBypassHttpErrorException(final HttpResponse httpResponse) {
final StatusLine status = httpResponse.getStatusLine();
if (httpResponse.containsHeader(BYPASS_HTTP_ERRORS_HEADER_NAME)) {
log.debug("Bypass http error: {}", status);
ListMultimap<String, String> headers = ArrayListMultimap.create();
headers.put(BYPASS_HTTP_ERRORS_HEADER_NAME, BYPASS_HTTP_ERRORS_HEADER_VALUE);
HttpClientUtils.closeQuietly(httpResponse);
throw new BypassHttpErrorException(status.getStatusCode(), status.getReasonPhrase(), headers);
}
}
@Override
public <T> T execute(HttpUriRequest request, HttpClientContext context, RequestFunction<T> func)
throws IOException, UnauthorizedAccessException {
HttpClient client = HttpClientBuilder.create().build();
try {
return func.run(client.execute(request, context));
} finally {
HttpClientUtils.closeQuietly(client);
}
}
@Override
public <T> T execute(HttpUriRequest request, HttpClientContext context, CredentialsProvider provider,
RequestFunction<T> func)
throws IOException, UnauthorizedAccessException {
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
try {
return func.run(client.execute(request, context));
} finally {
HttpClientUtils.closeQuietly(client);
}
}