下面列出了org.apache.http.client.methods.HttpGet#abort() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static byte[] getData(String url) {
byte[] data = null;
logger.debug(">>>请求地址:{}", url);
try {
HttpGet httpGet = new HttpGet(url);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
data = EntityUtils.toByteArray(entity);
EntityUtils.consume(entity);
} else {
httpGet.abort();
}
}
} catch (Exception e) {
logger.error(">>>请求异常", e);
}
return data;
}
private HttpResponse sendGet(HttpGet httpGet)
throws ClientProtocolException {
HttpResponse response;
if (appConfig.getAdminAuthMethod().equalsIgnoreCase(Config.TOKEN)) {
httpGet.setHeader(new BasicHeader(TOKEN, appConfig.getAdminToken()));
} else {
httpGet.setHeader(new BasicHeader(TOKEN, getAdminToken()));
}
try {
response = client.execute(httpGet);
} catch (ConnectException c) {
httpGet.abort();
throw new ServiceUnavailableException(c.getMessage());
} catch (IOException e) {
httpGet.abort();
throw new ClientProtocolException(
"IO Exception during GET request ", e);
}
return response;
}
@Test
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
instance = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
response = instance.execute(request);
try {
final HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
// Do not feel like reading the response body
// Call abort on the request object
request.abort();
} finally {
response.close();
}
}
@Test
public void whenSecuredRestApiIsConsumed_then200OK() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
int timeout = 20; // seconds
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1");
getMethod.setConfig(requestConfig);
int hardTimeout = 5; // seconds
TimerTask task = new TimerTask() {
@Override
public void run() {
getMethod.abort();
}
};
new Timer(true).schedule(task, hardTimeout * 1000);
HttpResponse response = httpClient.execute(getMethod);
System.out.println("HTTP Status of response: " + response.getStatusLine().getStatusCode());
}
private String getText(String redirectLocation) {
HttpGet httpget = new HttpGet(redirectLocation);
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = "";
try {
responseBody = httpclient.execute(httpget, responseHandler);
} catch (Exception e) {
e.printStackTrace();
responseBody = null;
} finally {
httpget.abort();
httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
public static String getText(String redirectLocation) {
HttpGet httpget = new HttpGet(redirectLocation);
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = "";
try {
responseBody = httpclient.execute(httpget, responseHandler);
} catch (Exception e) {
e.printStackTrace();
responseBody = null;
} finally {
httpget.abort();
// httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
/**
* 封装HTTP GET方法
*
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String get(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet();
httpGet.setURI(URI.create(url));
HttpResponse response = httpClient.execute(httpGet);
String httpEntityContent = getHttpEntityContent(response);
httpGet.abort();
return httpEntityContent;
}
/**
* HTTP Get 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url, Map<String, String> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
// logger.debug("url is:"+url);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
logger.error("HttpClient get request error : ", e);
ResultCode<String> reslut = new ResultCode<String>();
reslut.setCode(Messages.API_ERROR_CODE);
reslut.setMsg(Messages.API_ERROR_MSG);
return JsonMapper.toJsonString(reslut);
}
}
@Test
public void useApacheHttpClient() throws ClientProtocolException, IOException {
final URI uri = URI.create(getEndpoint().toString() + "$metadata");
for (int i = 0; i < LOOP_COUNT; i++) {
HttpGet get = new HttpGet(uri);
HttpResponse response = getHttpClient().execute(get);
assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
get.abort();
}
}
@Test
@RunAsClient
public void testHystrixStream(@ArquillianResource URL url) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
HttpGet get = new HttpGet(url + HystrixProperties.DEFAULT_STREAM_PATH);
try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(get)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertTrue(response.getFirstHeader("Content-Type").getValue().startsWith("text/event-stream"));
// Ignore the response body
get.abort();
}
}
@Test
public void useApacheHttpClient() throws ClientProtocolException, IOException {
final URI uri = URI.create(getEndpoint().toString() + "$metadata");
for (int i = 0; i < LOOP_COUNT; i++) {
HttpGet get = new HttpGet(uri);
HttpResponse response = getHttpClient().execute(get);
assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
get.abort();
}
}
public void cancelRunningQuery() {
final HttpGet method = this.httpCall;
if ( method != null ) {
method.abort();
}
}
public String doHttpGet(Context context, StatisCacheBean mStatisCacheBean) throws HttpDataConnectionException, HttpDataParserException {
String str = null;
if (context != null) {
if (DataStatistics.getInstance().isDebug()) {
Log.d(DataStatistics.TAG, "url:" + mStatisCacheBean.getCacheData());
}
if (mStatisCacheBean != null) {
StatisDBHandler.saveLocalCache(context, mStatisCacheBean);
if (DataUtils.getAvailableNetWorkInfo(context) != null) {
HttpGet httpGet = new HttpGet(mStatisCacheBean.getCacheData());
try {
HttpResponse httpResponse = this.mDefaultHttpClient.execute(httpGet);
if (httpResponse == null) {
try {
httpGet.abort();
this.mDefaultHttpClient.getConnectionManager().closeExpiredConnections();
} catch (Exception e) {
e.printStackTrace();
}
} else {
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (DataStatistics.getInstance().isDebug()) {
Log.d(DataStatistics.TAG, "responseCode:" + responseCode);
}
if (responseCode < 200 || responseCode >= 300) {
if (!DataStatistics.getInstance().isDebug() && (System.currentTimeMillis() - mStatisCacheBean.getCacheTime()) / 1000 >= 432000) {
StatisDBHandler.deleteByCacheId(context, mStatisCacheBean.getCacheId());
}
throw new HttpDataConnectionException(httpResponse.getStatusLine().toString());
} else if (httpResponse.getEntity() == null) {
try {
httpGet.abort();
this.mDefaultHttpClient.getConnectionManager().closeExpiredConnections();
} catch (Exception e2) {
e2.printStackTrace();
}
} else {
str = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
if (DataStatistics.getInstance().isDebug()) {
Log.d(DataStatistics.TAG, "result:" + str);
}
StatisDBHandler.deleteByCacheId(context, mStatisCacheBean.getCacheId());
try {
httpGet.abort();
this.mDefaultHttpClient.getConnectionManager().closeExpiredConnections();
} catch (Exception e22) {
e22.printStackTrace();
}
}
}
} catch (Exception e222) {
e222.printStackTrace();
throw new HttpDataParserException(e222);
} catch (Exception e2222) {
e2222.printStackTrace();
throw new HttpDataConnectionException(e2222);
} catch (Exception e22222) {
e22222.printStackTrace();
throw new HttpDataConnectionException(e22222);
} catch (Exception e222222) {
e222222.printStackTrace();
throw new HttpDataConnectionException(e222222);
} catch (Throwable th) {
try {
httpGet.abort();
this.mDefaultHttpClient.getConnectionManager().closeExpiredConnections();
} catch (Exception e2222222) {
e2222222.printStackTrace();
}
}
}
}
}
return str;
}
private void handleQuery(String queryHandlerPath, HttpServletRequest request, HttpServletResponse resp)
throws IOException, TransformerException, SAXException {
ModifiableSolrParams solrParameter = getSolrQueryParameter(request);
HttpGet solrHttpMethod = MCRSolrProxyServlet.getSolrHttpMethod(queryHandlerPath, solrParameter,
Optional.ofNullable(request.getParameter(QUERY_CORE_PARAMETER)).orElse(MCRSolrConstants.MAIN_CORE_TYPE));
try {
LOGGER.info("Sending Request: {}", solrHttpMethod.getURI());
HttpResponse response = httpClient.execute(solrHttpMethod);
int statusCode = response.getStatusLine().getStatusCode();
// set status code
resp.setStatus(statusCode);
boolean isXML = response.getFirstHeader(HTTP.CONTENT_TYPE).getValue().contains("/xml");
boolean justCopyInput = !isXML;
// set all headers
for (Header header : response.getAllHeaders()) {
LOGGER.debug("SOLR response header: {} - {}", header.getName(), header.getValue());
String headerName = header.getName();
if (NEW_HTTP_RESPONSE_HEADER.containsKey(headerName)) {
String headerValue = NEW_HTTP_RESPONSE_HEADER.get(headerName);
if (headerValue != null && headerValue.length() > 0) {
resp.setHeader(headerName, headerValue);
}
} else {
resp.setHeader(header.getName(), header.getValue());
}
}
HttpEntity solrResponseEntity = response.getEntity();
if (solrResponseEntity != null) {
try (InputStream solrResponseStream = solrResponseEntity.getContent()) {
if (justCopyInput) {
// copy solr response to servlet outputstream
OutputStream servletOutput = resp.getOutputStream();
IOUtils.copy(solrResponseStream, servletOutput);
} else {
MCRStreamContent solrResponse = new MCRStreamContent(solrResponseStream,
solrHttpMethod.getURI().toString(),
"response");
MCRLayoutService.instance().doLayout(request, resp, solrResponse);
}
}
}
} catch (IOException ex) {
solrHttpMethod.abort();
throw ex;
}
solrHttpMethod.releaseConnection();
}
/**
* Executes the download in a separate thread
*/
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
State state = new State(mInfo);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
try {
PowerManager pm = (PowerManager) mContext
.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
Constants.TAG);
wakeLock.acquire();
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
}
client = AndroidHttpClient.newInstance(userAgent(), mContext);
boolean finished = false;
while (!finished) {
Log.i(Constants.TAG, "Initiating request for download "
+ mInfo.mId);
HttpGet request = new HttpGet(state.mRequestUri);
try {
executeDownload(state, client, request);
finished = true;
} catch (RetryDownload exc) {
// fall through
} finally {
request.abort();
request = null;
}
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
}
finalizeDestinationFile(state);
finalStatus = Downloads.STATUS_SUCCESS;
} catch (StopRequest error) {
// remove the cause before printing, in case it contains PII
Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId
+ ": " + error.getMessage());
finalStatus = error.mFinalStatus;
// fall through to finally block
} catch (Throwable ex) { // sometimes the socket code throws unchecked
// exceptions
Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
// falls through to the code that reports an error
} finally {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (client != null) {
client.close();
client = null;
}
cleanupDestination(state, finalStatus);
notifyDownloadCompleted(finalStatus, state.mCountRetry,
state.mRetryAfter, state.mGotData, state.mFilename,
state.mNewUri, state.mMimeType);
mInfo.mHasActiveThread = false;
}
}
/**
* Executes the download in a separate thread
*/
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
State state = new State(mInfo, mService);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
try {
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
wakeLock.acquire();
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
Log.v(Constants.TAG, " at " + mInfo.mUri);
}
client = AndroidHttpClient.newInstance(userAgent(), mContext);
boolean finished = false;
while (!finished) {
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
Log.v(Constants.TAG, " at " + mInfo.mUri);
}
// Set or unset proxy, which may have changed since last GET
// request.
// setDefaultProxy() supports null as proxy parameter.
ConnRouteParams.setDefaultProxy(client.getParams(),
getPreferredHttpHost(mContext, state.mRequestUri));
HttpGet request = new HttpGet(state.mRequestUri);
try {
executeDownload(state, client, request);
finished = true;
} catch (RetryDownload exc) {
// fall through
} finally {
request.abort();
request = null;
}
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
Log.v(Constants.TAG, " at " + mInfo.mUri);
}
finalizeDestinationFile(state);
finalStatus = DownloaderService.STATUS_SUCCESS;
} catch (StopRequest error) {
// remove the cause before printing, in case it contains PII
Log.w(Constants.TAG,
"Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
error.printStackTrace();
finalStatus = error.mFinalStatus;
// fall through to finally block
} catch (Throwable ex) { // sometimes the socket code throws unchecked
// exceptions
Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
// falls through to the code that reports an error
} finally {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (client != null) {
client.close();
client = null;
}
cleanupDestination(state, finalStatus);
notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
state.mRedirectCount, state.mGotData, state.mFilename);
}
}
/**
* Executes the download in a separate thread
*/
@SuppressLint("Wakelock")
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
State state = new State(mInfo, mService);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
try {
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
wakeLock.acquire();
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
Log.v(Constants.TAG, " at " + mInfo.mUri);
}
client = AndroidHttpClient.newInstance(userAgent(), mContext);
boolean finished = false;
while (!finished) {
if (Constants.LOGV) {
Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
Log.v(Constants.TAG, " at " + mInfo.mUri);
}
// Set or unset proxy, which may have changed since last GET
// request.
// setDefaultProxy() supports null as proxy parameter.
ConnRouteParams.setDefaultProxy(client.getParams(),
getPreferredHttpHost(mContext, state.mRequestUri));
HttpGet request = new HttpGet(state.mRequestUri);
try {
executeDownload(state, client, request);
finished = true;
} catch (RetryDownload exc) {
// fall through
} finally {
request.abort();
request = null;
}
}
if (Constants.LOGV) {
Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
Log.v(Constants.TAG, " at " + mInfo.mUri);
}
finalizeDestinationFile(state);
finalStatus = DownloaderService.STATUS_SUCCESS;
} catch (StopRequest error) {
// remove the cause before printing, in case it contains PII
Log.w(Constants.TAG,
"Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
error.printStackTrace();
finalStatus = error.mFinalStatus;
// fall through to finally block
} catch (Throwable ex) { // sometimes the socket code throws unchecked
// exceptions
Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
// falls through to the code that reports an error
} finally {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (client != null) {
client.close();
client = null;
}
cleanupDestination(state, finalStatus);
notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
state.mRedirectCount, state.mGotData, state.mFilename);
}
}
public Bitmap Task(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
final Bitmap bitmap = BitmapFactory
.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
handlernum = -1;
Log.e("ImageDownloader", "Something went wrong while"
+ " retrieving bitmap from " + url + e.toString());
}
return null;
}
private Bitmap downloadBitmapWithClient(String url) {
final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");
HttpClientParams.setRedirecting(httpClient.getParams(), true);
final HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Header[] headers = response.getHeaders("Location");
if (headers != null && headers.length != 0) {
String newUrl = headers[headers.length - 1].getValue();
// call again with new URL
return downloadBitmap(newUrl);
} else {
return null;
}
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
// do your work here
return BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
request.abort();
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return null;
}
@Override
protected InputStream sendContent() {
try {
URI uri = get();
if (uri == null) {
throw new IllegalStateException("No uri for input");
}
HttpGet method = new HttpGet(uri);
HttpResponse response = client.execute(method, getContext());
StatusLine status = response.getStatusLine();
if (status.getStatusCode() >= 300) {
if (!method.isAborted()) {
method.abort();
}
throw new MarkLogicIOException("Could not read from "+uri.toString()+": "+status.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity == null) {
if (!method.isAborted()) {
method.abort();
}
throw new MarkLogicIOException("Received empty response to write for "+uri.toString());
}
InputStream stream = entity.getContent();
if (stream == null) {
if (!method.isAborted()) {
method.abort();
}
throw new MarkLogicIOException("Could not get stream to write for "+uri.toString());
}
return stream;
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}