下面列出了org.apache.http.client.methods.HttpGet#releaseConnection() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private byte[] readUrl(String url) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
return IOUtils.toByteArray(entity.getContent());
} finally {
if (response.getEntity() != null) {
EntityUtils.consume(response.getEntity());
}
httpGet.releaseConnection();
}
}
public static String getRequestAsString(String url)
throws UicdDeviceHttpConnectionResetException {
logger.info("get request to xmldumper:" + url);
String ret = "";
HttpClient client = HttpClientBuilder.create()
.setRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_REQUEST_RETRIES, true)).build();
HttpGet method = new HttpGet(url);
try {
HttpResponse response = client.execute(method);
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.warning(e.getMessage());
if (CONNECTION_RESET_KEYWORDS_LIST.stream().parallel().anyMatch(e.getMessage()::contains)) {
throw new UicdDeviceHttpConnectionResetException(e.getMessage());
}
} finally {
method.releaseConnection();
}
return ret;
}
@Test
public void testEncodedURL() throws Exception {
String id = "A%20B%20C"; // "A B C"
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet("http://localhost:" + PORT + "/bookstore/books/" + id);
try {
CloseableHttpResponse response = client.execute(get);
assertEquals("Encoded path '/" + id + "' is not handled successfully",
200, response.getStatusLine().getStatusCode());
assertEquals("Book description for id " + id + " is wrong",
"CXF in Action A B C", EntityUtils.toString(response.getEntity()));
} finally {
// Release current connection to the connection pool once you are done
get.releaseConnection();
}
}
public GithubProfileInfo info(@NotNull String accessToken, @NotNull GithubEmails emails) throws IOException, GithubException {
HttpGet get = new HttpGet(USER);
get.addHeader("Authorization", "token " + accessToken);
try {
HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();
if (entity == null) throw new IOException(new NullPointerException("HttpEntity is null"));
JsonElement element = parser.parse(new InputStreamReader(entity.getContent()));
if (!element.isJsonObject()) throw new IOException("Response is not of type JsonObject");
JsonObject obj = new JsonObject();
if (obj.has("message")) throw GithubException.fromMessage(obj);
else return new GithubProfileInfo(element.getAsJsonObject(), emails);
} catch (JsonParseException | NullPointerException ex) {
throw new IOException(ex);
} finally {
get.releaseConnection();
}
}
public BackendResponse get(String url) {
String uri = backendMockUriPrefix + url;
HttpGet httpGet = new HttpGet(uri);
try {
HttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failure: " + response.getStatusLine());
}
HttpEntity entity = response.getEntity();
BackendResponse backendResponse = BackendResponse.fromJson(jsonFactory, entity.getContent());
// ensure it is fully consumed
EntityUtils.consume(entity);
return backendResponse;
} catch (Exception e) {
throw new RuntimeException("Failure retrieving: " + uri, e);
} finally {
httpGet.releaseConnection();
}
}
private String getHttpResponse(String url) {
DefaultHttpClient client = new DefaultHttpClient();
String msg = null;
int retryTimes = 0;
while (msg == null && retryTimes < HTTP_RETRY) {
retryTimes++;
HttpGet request = new HttpGet(url);
try {
request.addHeader("accept", "application/json");
HttpResponse response = client.execute(request);
msg = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.warn("Failed to fetch http response. Retry={}", retryTimes, e);
} finally {
request.releaseConnection();
}
}
return msg;
}
public HttpResponse doGet(String resourcePath) throws RestClientException {
HttpGet get = new HttpGet(resourcePath);
setAuthHeader(get);
try {
return httpClient.execute(get);
} catch (IOException e) {
String errorMsg = "Error while executing GET statement";
log.error(errorMsg, e);
throw new RestClientException(errorMsg, e);
} finally {
get.releaseConnection();
}
}
/**
* 获取二进制文件流
* @param url
* @return
* @throws Exception
*/
public static ByteArrayOutputStream doFileGetHttps(String url) throws Exception {
initSSLContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
int responseCode = response.getStatusLine().getStatusCode();
Logger.info("httpClient get 响应状态responseCode="+responseCode+", 请求 URL="+url);
if(responseCode == RSP_200 || responseCode == RSP_400){
InputStream inputStream = response.getEntity().getContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buff[] = new byte[4096];
int counts = 0;
while ((counts = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, counts);
}
outputStream.flush();
outputStream.close();
httpGet.releaseConnection();
return outputStream;
}else{
httpGet.releaseConnection();
throw new Exception("接口请求异常:接口响应状态="+responseCode);
}
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static JSONObject httpGet(String url,String tokenKey,String token)
{
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
HttpGet request = new HttpGet(url);
if(!StringUtils.isEmpty(tokenKey)){
request.setHeader(tokenKey,token);
}
request.setConfig(requestConfig);
try
{
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
}
else
{
logger.error("get请求提交失败:" + url);
}
}
catch (IOException e)
{
logger.error("get请求提交失败:" + url, e);
}
finally
{
request.releaseConnection();
}
return jsonResult;
}
protected String fetchURLasString(String url) throws IOException, ParseException {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
httpGet.releaseConnection();
return body;
}
/**
* 普通GET请求
*
* @param uri
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static String doGet(String uri) throws ClientProtocolException, IOException {
String html = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
html = EntityUtils.toString(entity);
EntityUtils.consume(entity);
}
httpGet.releaseConnection();
response.close();
return html;
}
@Override
public Iterator<Volume> iterator() {
final FilteredUriBuilder uri = new FilteredUriBuilder(
new UncheckedUriBuilder(super.baseUri().toString()), this.filters
);
final HttpGet get = new HttpGet(uri.build());
try {
return super.client().execute(
get,
new ReadJsonObject(
new MatchStatus(get.getURI(), HttpStatus.SC_OK)
)
).getJsonArray("Volumes").stream()
.map(json -> (JsonObject) json)
.map(
volume -> (Volume) new RtVolume(
volume,
super.client(),
URI.create(
String.format("%s/%s",
super.baseUri().toString(),
volume.getString("Name")
)
),
super.docker()
)
).collect(Collectors.toList())
.iterator();
} catch (final IOException err) {
throw new RuntimeException(
String.format("Error executing GET on %s", super.baseUri())
);
} finally {
get.releaseConnection();
}
}
/**
* Sets up a raw http(s) connection to Fbox and gets xml response as XML
* Document, ready for parsing.
*
* @return
*/
public Document getFboxXmlResponse(String url) {
Document tr064response = null;
HttpGet httpGet = new HttpGet(url);
boolean exceptionOccurred = false;
try {
synchronized (_httpClient) {
CloseableHttpResponse resp = _httpClient.execute(httpGet, _httpClientContext);
int responseCode = resp.getStatusLine().getStatusCode();
if (responseCode == 200) {
HttpEntity entity = resp.getEntity();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
tr064response = db.parse(entity.getContent());
EntityUtils.consume(entity);
} else {
logger.error("Failed to receive valid response from httpGet");
}
}
} catch (Exception e) {
exceptionOccurred = true;
logger.error("Failed to receive valid response from httpGet: {}", e.getMessage());
} finally {
// Make sure connection is released. If error occurred make sure to print in log
if (exceptionOccurred) {
logger.error("Releasing connection to FritzBox because of error!");
} else {
logger.debug("Releasing connection");
}
httpGet.releaseConnection();
}
return tr064response;
}
/**
* Extracts the minion job response by calling the job resource.
*
* @return the host response or null if none is available encoded in json.
* @throws SaltApiException
* if the salt-api response does not conform to the expected
* format.
* @throws InterruptedException
*/
protected String extractOutputForJid(HttpClient client, String authToken, String jid, String minionId)
throws IOException, SaltApiException, InterruptedException {
String jidResource = String.format("%s%s/%s", saltEndpoint, JOBS_RESOURCE, jid);
HttpGet get = httpFactory.createHttpGet(jidResource);
get.setHeader(SALT_AUTH_TOKEN_HEADER, authToken);
get.setHeader(REQUEST_ACCEPT_HEADER_NAME, JSON_RESPONSE_ACCEPT_TYPE);
HttpResponse response = retryExecutor.execute(logWrapper, client, get, numRetries);
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String entityResponse = extractBodyFromEntity(entity);
Gson gson = new Gson();
Map<String, List<Map<String, Object>>> result = gson.fromJson(entityResponse, JOB_RESPONSE_TYPE);
List<Map<String, Object>> responses = result.get(SALT_OUTPUT_RETURN_KEY);
if (responses.size() > 1) {
throw new SaltApiException("Too many responses received: " + response);
} else if (responses.size() == 1) {
Map<String, Object> minionResponse = responses.get(0);
if (minionResponse.containsKey(minionId)) {
logWrapper.debug("Received response for jobs/%s = %s", jid, response);
Object responseObj = minionResponse.get(minionId);
return gson.toJson(responseObj);
}
}
return null;
} else {
return null;
}
} finally {
closeResource(response.getEntity());
get.releaseConnection();
}
}
public int getHttpStatusFromGet (String url) throws IOException {
String encodedUrl = getEncodedUrl(url);
CloseableHttpClient httpClient = getHttpClient(encodedUrl);
HttpGet get = new HttpGet(encodedUrl);
try {
LOGGER.debug("executing get request to retrieve status on " + get.getURI());
HttpResponse status = httpClient.execute(get);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("received " + status + " from get request");
for (Header h : get.getAllHeaders()) {
LOGGER.debug("header : " + h.getName() + " " +h.getValue());
}
}
return status.getStatusLine().getStatusCode();
} catch (UnknownHostException uhe) {
LOGGER.warn("UnknownHostException on " + encodedUrl);
return HttpStatus.SC_NOT_FOUND;
} catch (IOException ioe) {
LOGGER.warn("IOException on " + encodedUrl);
return HttpStatus.SC_NOT_FOUND;
}finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
get.releaseConnection();
httpClient.close();
}
}
@Nullable
public FacebookToken verify(@NotNull String accessToken) throws IOException, FacebookOAuthException {
HttpGet get = new HttpGet(DEBUG_TOKEN + "?input_token=" + accessToken + "&access_token=" + appToken);
try {
HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();
if (entity == null) throw new IOException(new NullPointerException("HttpEntity is null"));
JsonElement element = parser.parse(new InputStreamReader(entity.getContent()));
if (!element.isJsonObject()) throw new IOException("Response is not of type JsonObject");
JsonObject obj = element.getAsJsonObject();
if (obj.has("data")) {
FacebookToken token = new FacebookToken(obj.getAsJsonObject("data"));
if (token.valid && appId.equals(token.appId)) return token;
else return null;
} else if (obj.has("error")) {
throw new FacebookOAuthException(obj.getAsJsonObject("error"));
} else {
throw new IOException("What is that? " + obj);
}
} catch (JsonParseException | NullPointerException ex) {
throw new IOException(ex);
} finally {
get.releaseConnection();
}
}
private String verifyUUIDToken(String token, String newUri,
Header[] headers)
throws ClientProtocolException {
HttpGet httpGet = new HttpGet(newUri);
try {
httpGet.setHeader("Accept", APPLICATION_JSON);
httpGet.setHeader("Content-Type", APPLICATION_JSON);
if (headers != null) {
for (Header header : headers) {
httpGet.setHeader(header);
}
}
HttpResponse response = sendGet(httpGet);
HttpEntity entity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
InputStream instream;
try {
if (code == 404) {
instream = entity.getContent();
instream.close();
//
// Don't log the whole token, just the last ten characters
//
throw new AuthException("Authorization failed for user token ending with: "
+ token.substring(token.length() - 10));
}
if (code != 200) {
adminToken = null;
instream = entity.getContent();
instream.close();
String reasonPhrase = response.getStatusLine().getReasonPhrase();
throw new AuthException("Failed to validate via HTTP " + code + " " + reasonPhrase);
}
} catch (IOException e) {
throw new ClientProtocolException("IO Exception: problem closing stream ", e);
}
return parseResponse(response);
} finally {
httpGet.releaseConnection();
}
}
/**
* Download link and have it be the response.
* @param req the http request
* @param resp the http response
* @param link the link to download
* @param c the cookie to set if any
* @throws IOException on any error.
*/
private static void proxyLink(HttpServletRequest req,
HttpServletResponse resp, URI link, Cookie c, String proxyHost)
throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
client
.getParams()
.setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.BROWSER_COMPATIBILITY)
.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// Make sure we send the request from the proxy address in the config
// since that is what the AM filter checks against. IP aliasing or
// similar could cause issues otherwise.
InetAddress localAddress = InetAddress.getByName(proxyHost);
if (LOG.isDebugEnabled()) {
LOG.debug("local InetAddress for proxy host: {}", localAddress);
}
client.getParams()
.setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);
HttpGet httpGet = new HttpGet(link);
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getHeaderNames();
while(names.hasMoreElements()) {
String name = names.nextElement();
if(passThroughHeaders.contains(name)) {
String value = req.getHeader(name);
if (LOG.isDebugEnabled()) {
LOG.debug("REQ HEADER: {} : {}", name, value);
}
httpGet.setHeader(name, value);
}
}
String user = req.getRemoteUser();
if (user != null && !user.isEmpty()) {
httpGet.setHeader("Cookie",
PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
}
OutputStream out = resp.getOutputStream();
try {
HttpResponse httpResp = client.execute(httpGet);
resp.setStatus(httpResp.getStatusLine().getStatusCode());
for (Header header : httpResp.getAllHeaders()) {
resp.setHeader(header.getName(), header.getValue());
}
if (c != null) {
resp.addCookie(c);
}
InputStream in = httpResp.getEntity().getContent();
if (in != null) {
IOUtils.copyBytes(in, out, 4096, true);
}
} finally {
httpGet.releaseConnection();
}
}
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();
}
@Override
public T execute() throws ClientProtocolException, IOException {
HttpGet get = new HttpGet(InstagramConstants.API_URL + getUrl());
this.applyHeaders(get);
HttpResponse response = api.executeHttpRequest(get);
int resultCode = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity());
get.releaseConnection();
return parseResult(resultCode, content);
}