下面列出了org.apache.http.client.utils.HttpClientUtils#closeQuietly ( ) 实例代码,或者点击链接到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);
}
}
@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);
}
}
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);
}
}
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();
}
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;
}
@SuppressWarnings("unchecked")
private R instantiateResponse(final HttpResponse res) {
R odataResponse;
try {
odataResponse = (R) ((AbstractODataRequest) odataRequest).getResponseTemplate().initFromEnclosedPart(res
.getEntity().getContent());
} catch (Exception e) {
LOG.error("Error instantiating odata response", e);
odataResponse = null;
} finally {
HttpClientUtils.closeQuietly(res);
}
return odataResponse;
}
@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);
}
}
public RestResult(HttpResponse response, String fileName, String url) {
this.url = url;
// If the query got a success status stream the result immediately to the target file.
// If not, the result should be small and contain diagnostic info so stgre it in the response string.
File output = new File(fileName);
if(output.exists()){
FileUtils.deleteQuietly(output);
}
try(OutputStream out = new FileOutputStream(fileName)){
processCodes(response);
if (status == 200) {
response.getEntity().writeTo(out);
} else {
responseString = EntityUtils.toString(response.getEntity());
IOUtils.write(reason + SystemProperties.lineSeparator + responseString, out, Constants.UTF_8);
}
} catch (Exception e) {
logger.error( "Error Streaming Response To OutputStream", e);
throw new RuntimeException();
}
finally {
HttpClientUtils.closeQuietly(response);
}
}
@Override
public synchronized void close() throws IOException {
if (httpClient != null && httpClientCreated) {
HttpClientUtils.closeQuietly(httpClient);
}
isClosed = true;
}
@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);
}
@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);
}
}
/**
* 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);
}
@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);
}
}
@Override
public HttpResponse handleResponse(HttpResponse response) throws BintrayCallException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusNotOk(statusCode)) {
BintrayCallException bce = new BintrayCallException(response);
//We're using CloseableHttpClient so it's ok
HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
throw bce;
}
//Response entity might be null, 500 and 405 also give the html itself so skip it
byte[] entity = new byte[0];
if (response.getEntity() != null && statusCode != 500 && statusCode != 405) {
try {
entity = IOUtils.toByteArray(response.getEntity().getContent());
} catch (IOException | NullPointerException e) {
//Null entity - Ignore
} finally {
HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
}
}
HttpResponse newResponse = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(response.getStatusLine(),
new HttpClientContext());
newResponse.setEntity(new ByteArrayEntity(entity));
newResponse.setHeaders(response.getAllHeaders());
return newResponse;
}
private TransmissionVO execute(JSONObject params) {
TransmissionVO ret = null;
if(httpClient == null) {
initialize();
}
HttpPost httpPost = new HttpPost(baseUrl);
CloseableHttpResponse response = null;
log.debug(params.toString());
try {
httpPost.setEntity(new StringEntity(params.toString(), "UTF-8"));
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 409) {
xTransmissionSessionId = response.getFirstHeader("X-Transmission-Session-Id").getValue();
response.close();
httpClient.close();
initialize();
response = httpClient.execute(httpPost);
}
log.debug("transmission-execute-response-code: " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
JSONObject resJson = new JSONObject(EntityUtils.toString(response.getEntity()));
log.debug(resJson.toString());
ret = new TransmissionVO();
if (resJson.has("result")) {
ret.setResult(resJson.getString("result"));
}
if (resJson.has("arguments")) {
ret.setArguments(resJson.getJSONObject("arguments"));
}
}
} catch (IOException | ParseException | JSONException e) {
log.error(e.getMessage());
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
httpClient = null;
}
HttpClientUtils.closeQuietly(response);
return ret;
}
/**
*
* @Title: exec
* @Description: Execute HTTP request
* @param @param hreq
* @param @param ureq
* @param @return
* @return HttpRsp
* @throws
*/
private HttpRsp exec(HttpRequestBase req)
{
CloseableHttpResponse hr = null;
HttpRsp rsp = new HttpRsp();
try
{
/* Send HTTP request */
hr = hc.execute(req);
HttpEntity he = hr.getEntity();
if (null != he)
{
/* Receive HTTP response */
String body = EntityUtils.toString(he, Charsets.UTF_8.getCname());
if (null == body)
{
body = StringUtils.EMPTY;
}
rsp.setBody(body);
}
else
{
log.warn("HTTP response is null.");
}
hr.setReasonPhrase("");
rsp.setStatus(hr.getStatusLine().toString());
rsp.setStatusCode(hr.getStatusLine().getStatusCode());
rsp.setHeaders(new HashMap<String, String>());
for (Header hdr : hr.getAllHeaders())
{
rsp.getHeaders().put(hdr.getName(), hdr.getValue());
}
}
catch(Throwable e)
{
log.error("Http request failed.", e);
}
finally
{
HttpClientUtils.closeQuietly(hr);
}
return rsp;
}
@Test
public void test() throws IOException, InterruptedException {
LookoutConfig config = new LookoutConfig();
final LookoutRegistry lookoutRegistry = new LookoutRegistry(Clock.SYSTEM, null, config,
null, 1000L);
// 通常只会有一个LookoutRegistry
final Collection<LookoutRegistry> lookoutRegistries = new ArrayList<LookoutRegistry>(1);
lookoutRegistries.add(lookoutRegistry);
// 使用者需要自行构建该 PollerController
// 能不能将逻辑做到 client 里?
// Registry registry = client.getRegistry();
PollerController pc = new PollerController(lookoutRegistry);
bind(pc, lookoutRegistries);
MetricsHttpExporter e = new MetricsHttpExporter(pc);
e.start();
// SimpleLookoutClient client = new SimpleLookoutClient("foo", config, lookoutRegistry, ssr);
Thread.sleep(1200);
CloseableHttpClient hc = HttpClients.createDefault();
try {
HttpClientUtils.closeQuietly(hc.execute(RequestBuilder.get(
"http://localhost:19399/clear").build()));
HttpUriRequest request = RequestBuilder.get("http://localhost:19399/get?success=1,2,3")
.build();
CloseableHttpResponse response = hc.execute(request);
try {
String content = EntityUtils.toString(response.getEntity());
JSONObject r = JSON.parseObject(content);
assertNotNull(r);
} finally {
HttpClientUtils.closeQuietly(response);
}
} finally {
HttpClientUtils.closeQuietly(hc);
e.close();
}
}
@Override
public void close() {
executorService.shutdown();
HttpClientUtils.closeQuietly(client);
}