本文整理汇总了Java中org.apache.http.client.utils.HttpClientUtils.closeQuietly方法的典型用法代码示例。如果您正苦于以下问题:Java HttpClientUtils.closeQuietly方法的具体用法?Java HttpClientUtils.closeQuietly怎么用?Java HttpClientUtils.closeQuietly使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.client.utils.HttpClientUtils
的用法示例。
在下文中一共展示了HttpClientUtils.closeQuietly方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getPage
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
public String getPage(String symbol) {
String rtn = null;
String url = String.format("https://finance.yahoo.com/quote/%s/?p=%s", symbol, symbol);
HttpGet request = new HttpGet(url);
System.out.println(url);
request.addHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
try {
HttpResponse response = client.execute(request, context);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
rtn = result.toString();
HttpClientUtils.closeQuietly(response);
} catch (Exception ex) {
System.out.println("Exception");
System.out.println(ex);
}
System.out.println("returning from getPage");
return rtn;
}
示例2: run
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
@Override
public void run() {
String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());
logger.info("报工开始了,今天是:" + dateStr);
isFailed = true;
while (isFailed) {
if (curr_try_times >= MAX_TRY_TIMES) {
try {
HttpClientUtils.closeQuietly(client);
logger.info("连续尝试次数超过" + MAX_TRY_TIMES + "次,先休息1小时...");
Thread.sleep(1000 * 3600);
curr_try_times = 0;
} catch (InterruptedException e) {
logger.error("线程休息出错:", e);
}
}
curr_try_times++;
start();
}
}
示例3: sendRecordingRequest
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
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 "";
}
示例4: executeRequest
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
/**
* 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);
}
}
示例5: submitNewWorkflow
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
@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);
}
}
示例6: postOverHttp
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
/** Helper method to post data over Http */
private CloseableHttpResponse postOverHttp(Object dataToPost, String pathSuffix) {
CloseableHttpResponse httpResponse = null;
HttpPost httpPostRequest;
httpPostRequest = new HttpPost(fluxEndpoint + pathSuffix);
try {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
objectMapper.writeValue(byteArrayOutputStream, dataToPost);
httpPostRequest.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.APPLICATION_JSON));
httpResponse = closeableHttpClient.execute(httpPostRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode >= Response.Status.OK.getStatusCode() && statusCode < Response.Status.MOVED_PERMANENTLY.getStatusCode() ) {
logger.trace("Posting over http is successful. Status code: {}", statusCode);
} else {
logger.error("Did not receive a valid response from Flux core. Status code: {}, message: {}", statusCode, EntityUtils.toString(httpResponse.getEntity()));
HttpClientUtils.closeQuietly(httpResponse);
throw new RuntimeCommunicationException("Did not receive a valid response from Flux core");
}
} catch (IOException e) {
logger.error("Posting over http errored. Message: {}", e.getMessage(), e);
HttpClientUtils.closeQuietly(httpResponse);
throw new RuntimeCommunicationException("Could not communicate with Flux runtime: " + fluxEndpoint);
}
return httpResponse;
}
示例7: executeStream
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
private HttpStreamResponse executeStream(HttpRequestBase requestBase) throws OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException {
applyHeadersCommonToAllRequests(requestBase);
activeCount.incrementAndGet();
CloseableHttpResponse response = client.execute(requestBase);
StatusLine statusLine = response.getStatusLine();
int status = statusLine.getStatusCode();
if (status < 200 || status >= 300) {
activeCount.decrementAndGet();
HttpClientUtils.closeQuietly(response);
requestBase.reset();
throw new IOException("Bad status : " + statusLine);
}
return new HttpStreamResponse(statusLine.getStatusCode(),
statusLine.getReasonPhrase(),
response,
response.getEntity().getContent(),
requestBase,
activeCount);
}
示例8: execute
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
public String execute(HttpRequestBase post) throws UserErrorException {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
resp = client.execute(post);
HttpEntity entity = resp.getEntity();
String body = EntityUtils.toString(entity);
int statCode = resp.getStatusLine().getStatusCode();
if (statCode != 200) {
String msg = "Expected 200 but got " + statCode;
logger.warn("About to throw " + msg + " body was " + body);
throw new RuntimeException(msg);
}
return body;
}
catch (Throwable e) {
throw new UserErrorException("Error performing remote server post", e);
}
finally {
HttpClientUtils.closeQuietly(resp);
HttpClientUtils.closeQuietly(client);
}
}
示例9: loadDumps
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
protected void loadDumps() {
HttpClient client = new DefaultHttpClient();
if (!downloadFolder.exists()) {
downloadFolder.mkdirs();
}
try {
File dumpFile;
for (int i = 0; i < dumps.length; ++i) {
dumpFile = new File(downloadFolder.getAbsolutePath() + File.separator + extractFileName(dumps[i]));
if (!dumpFile.exists()) {
LOGGER.info("Start loading dump \"" + dumps[i] + "\".");
try {
dumpFile = loadDump(dumps[i], dumpFile, client);
} catch (Exception e) {
throw new RuntimeException(
"Exception while trying to download dump from \"" + dumps[i] + "\".", e);
}
} else {
LOGGER.info(dumpFile.getAbsolutePath() + " is already existing. It won't be downloaded.");
}
dumps[i] = dumpFile.getAbsolutePath();
}
} finally {
HttpClientUtils.closeQuietly(client);
}
}
示例10: HttpRequestResponse
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
/**
* Constructs a {@link HttpRequestResponse} from a {@link HttpResponse} by
* consuming the {@link HttpResponse}'s {@link InputStream} and closing the
* original {@link HttpResponse}. This constructor uses a particular
* fall-back character encoding to interpret the content with should the
* character encoding not be possible to determine from the response itself.
*
* @param httpResponse
* A {@link HttpResponse} that will be consumed. That is, the
* {@link HttpResponse}'s {@link InputStream} will be consumed
* and closed when the method returns.
* @param fallbackCharset
* The character set used to interpret the message body, if the
* character encoding cannot be determined from the response
* itself.
* @throws IOException
*/
public HttpRequestResponse(CloseableHttpResponse httpResponse, Charset fallbackCharset) throws IOException {
try {
this.statusCode = httpResponse.getStatusLine().getStatusCode();
this.headers = Arrays.asList(httpResponse.getAllHeaders());
Charset responseCharset = determineCharset(httpResponse);
Charset charset = responseCharset == null ? fallbackCharset : responseCharset;
// http response may not contain a message body, for example on 204
// (No Content) responses
if (httpResponse.getEntity() != null) {
this.responseBody = EntityUtils.toString(httpResponse.getEntity(), charset);
} else {
this.responseBody = null;
}
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}
}
示例11: executeHttpRequest
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
protected Response executeHttpRequest(RequestBuilder httpRequest){
CloseableHttpClient client = getClient();
initHeaders(httpRequest);
initParams(httpRequest);
Response response = null;
CloseableHttpResponse resp = null;
if( entity != null ){
httpRequest.setEntity(entity);
}
try {
final HttpUriRequest uriRequest = httpRequest.build();
resp = client.execute(uriRequest);
// but make sure the response gets closed no matter what
// even if do not care about its content
response = new Response(resp);
response.setMethod(httpRequest.getMethod());
response.setRequestLine(uriRequest.getRequestLine().toString());
} catch (Exception e) {
// TODO: log the error
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(client);
}
return response;
}
示例12: download
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
public void download(String path) throws IOException {
final String url = baseUrl.endsWith("/") ? baseUrl + path : baseUrl + "/" + path;
final HttpGet httpGet = new HttpGet(url);
final HttpResponse response = httpClient.execute(httpGet);
try {
if (!isSuccess(response)) {
System.err.println(url);
System.err.println(response.getStatusLine());
if (response.getStatusLine().getStatusCode() != 404) {
throw new IOException(response.getStatusLine().toString());
}
}
}
finally {
HttpClientUtils.closeQuietly(response);
}
}
示例13: executeGetOrHead
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
protected CloseableHttpResponse executeGetOrHead(HttpRequestBase method) throws IOException {
final CloseableHttpResponse httpResponse = performHttpRequest(method);
// Consume content for non-successful, responses. This avoids the connection being left open.
if (!wasSuccessful(httpResponse)) {
CloseableHttpResponse response = new AutoClosedHttpResponse(httpResponse);
HttpClientUtils.closeQuietly(httpResponse);
return response;
}
return httpResponse;
}
示例14: load
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
@Override
public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
final URI uri = root.resolve("./" + key.getHashCode());
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Response for GET {}: {}", safeUri(uri), statusLine);
}
int statusCode = statusLine.getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
reader.readFrom(response.getEntity().getContent());
return true;
} else if (statusCode == 404) {
return false;
} else {
// TODO: We should consider different status codes as fatal/recoverable
throw new BuildCacheException(String.format("For key '%s', using %s response status %d: %s", key, getDescription(), statusCode, statusLine.getReasonPhrase()));
}
} catch (IOException e) {
// TODO: We should consider different types of exceptions as fatal/recoverable.
// Right now, everything is considered recoverable.
throw new BuildCacheException(String.format("loading key '%s' from %s", key, getDescription()), e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
示例15: downloadData
import org.apache.http.client.utils.HttpClientUtils; //导入方法依赖的package包/类
public void downloadData(String symbol, long startDate, long endDate, String crumb) {
String filename = String.format("%s.csv", symbol);
String url = String.format("https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=1d&events=history&crumb=%s", symbol, startDate, endDate, crumb);
HttpGet request = new HttpGet(url);
System.out.println(url);
request.addHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
try {
HttpResponse response = client.execute(request, context);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String reasonPhrase = response.getStatusLine().getReasonPhrase();
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(String.format("statusCode: %d", statusCode));
System.out.println(String.format("reasonPhrase: %s", reasonPhrase));
if (entity != null) {
BufferedInputStream bis = new BufferedInputStream(entity.getContent());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filename)));
int inByte;
while((inByte = bis.read()) != -1)
bos.write(inByte);
bis.close();
bos.close();
}
HttpClientUtils.closeQuietly(response);
} catch (Exception ex) {
System.out.println("Exception");
System.out.println(ex);
}
}