下面列出了org.apache.http.client.methods.CloseableHttpResponse#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
FramedStream executeFramedStream(
final RequestBuilder requestBuilder,
@Nullable final RequestOptions requestOptions
)
throws IOException, NomadException {
final HttpUriRequest request = buildRequest(requestBuilder, requestOptions);
CloseableHttpResponse response = httpClient.execute(request);
try {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw ErrorResponseException.signaledInStatus(request, response);
}
return new FramedStream(response);
} catch (Throwable e) {
response.close();
throw e;
}
}
/**
* 执行GET请求
*
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public String doGet(String url) throws ClientProtocolException, IOException {
// 创建http GET请求
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(this.requestConfig);
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
public JsonNode getAllTablesFromPinot() throws IOException {
HttpGet tablesReq = new HttpGet(PINOT_TABLES_ENDPOINT);
LOG.info("Retrieving datasets: {}", tablesReq);
CloseableHttpResponse tablesRes = pinotControllerClient.execute(pinotControllerHost, tablesReq);
JsonNode tables = null;
try {
if (tablesRes.getStatusLine().getStatusCode() != 200) {
throw new IllegalStateException(tablesRes.getStatusLine().toString());
}
InputStream tablesContent = tablesRes.getEntity().getContent();
tables = OBJECT_MAPPER.readTree(tablesContent).get("tables");
} catch (Exception e) {
LOG.error("Exception in loading collections", e);
} finally {
if (tablesRes.getEntity() != null) {
EntityUtils.consume(tablesRes.getEntity());
}
tablesRes.close();
}
return tables;
}
protected void closeHttpConnections() {
for (CloseableHttpResponse response : httpResponses) {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOGGER.error("Could not close http connection", e);
}
}
}
httpResponses.clear();
}
public void sendMessage(String player) {
setConfig();
if ( webhook == null ) {
return;
}
Map<String, String> keys = new HashMap<>();
keys.put("game", root.getGameName());
//keys.put("gameName", StringUtils.defaultIfBlank(root.getGameData().getUsersGameName(), "[none]"));
keys.put("round", gameUiManager.getCurrentRound().getRoundName());
keys.put("current", StringUtils.defaultIfBlank(playerNameMappings.get(player), player));
keys.put("previous", StringUtils.defaultIfBlank(observer.getFormerPlayer().getId(), "[none]"));
String msgBody = StringSubstitutor.replace(body, keys);
log.debug("Sending message '{}' to Discord for user {}", msgBody, player);
HttpPost httpPost = new HttpPost(webhook);
try {
httpPost.setEntity(new StringEntity(msgBody));
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
httpPost.setHeader(HttpHeaders.USER_AGENT, "18xx Rails");
CloseableHttpResponse response = httpClient.execute(httpPost);
if ( response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT ) {
log.debug("Unexpected Discord response: {}", response);
}
response.close();
}
catch (IOException e) {
log.error("Error sending message to Discord", e);
}
}
/**
* Checks the status code of the response and if it's considered as successful response, then
* this method just returns back. Else it {@link CloseableHttpResponse#close() closes the
* response} and throws an {@link IOException} for the unsuccessful response.
*
* @param httpMethod The HTTP method that was used for the source request
* @param sourceURL The URL of the source request
* @param response The response to the source request
* @throws IOException Thrown if the response was considered unsuccessful
*/
private void requireSuccessStatus(final String httpMethod, final URL sourceURL, final CloseableHttpResponse response) throws IOException {
if (this.checkStatusCode(httpMethod, sourceURL, response)) {
return;
}
// this is now considered an unsuccessful response, so close the response and throw an exception
try {
response.close();
} catch (Exception e) {
// log and move on
Message.debug("Could not close the HTTP response for url=" + sourceURL, e);
}
throw new IOException("Failed response to request '" + httpMethod + " " + sourceURL + "' " + response.getStatusLine().getStatusCode()
+ " - '" + response.getStatusLine().getReasonPhrase());
}
protected void closeHttpConnections() {
for (CloseableHttpResponse response : httpResponses) {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOGGER.error("Could not close http connection", e);
}
}
}
httpResponses.clear();
}
public static String contentAsString(URI uri, Credentials auth, ProgressMonitor<Long> monitor) throws IOException {
CloseableHttpResponse rsp = get(uri,auth);
try {
if (rsp.getStatusLine().getStatusCode() != 200) {
throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
}
HttpEntity entity = rsp.getEntity();
ContentType ct = ContentType.get(entity);
Charset cs = ct.getCharset();
if (cs == null) cs = StandardCharsets.UTF_8;
long length = entity.getContentLength();
int clength = (int)length;
if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;
try (InputStream is = entity.getContent();
ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
copy(is, os, length, monitor);
EntityUtils.consume(entity);
return new String(os.toByteArray(), cs);
}
} finally {
rsp.close();
}
}
protected void reportEventAsHttpRequest() throws IOException {
final String url = bounceProxyControllerUrl.buildReportShutdownUrl();
logger.debug("Using monitoring service URL: {}", url);
HttpPut putReportShutdown = new HttpPut(url.trim());
CloseableHttpResponse response = null;
try {
response = httpclient.execute(putReportShutdown);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) {
// unexpected response
logger.error("Failed to send shutdown notification: {}", response);
throw new JoynrHttpException(statusCode,
"Failed to send shutdown notification. Bounce Proxy still registered at Monitoring Service.");
} else {
logger.debug("Successfully sent shutdown notification");
}
} finally {
if (response != null) {
response.close();
}
}
}
public void closeResponse(CloseableHttpResponse response) {
if (response != null) {
try {
response.close();
} catch (IOException e) {
throw new AssertionError("Could not close http connection", e);
}
}
}
private List<ObjectNode> execute(URI uri) {
Objects.requireNonNull(uri);
List<ObjectNode> results = new ArrayList<>();
HttpRequestBase httpRequest = prepareHttpRequest(uri);
CloseableHttpResponse response = null;
String entityString;
try {
response = httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
// TODO: handle retry
if (response.getStatusLine().getStatusCode() == 200 && entity != null) {
entityString = EntityUtils.toString(entity);
if ( !entityString.equals("{}") && !entityString.equals("[]") ) {
JsonNode jsonNode = mapper.readValue(entityString, JsonNode.class);
results = parse(jsonNode);
}
}
} catch (IOException ex) {
LOGGER.error("IO error:\n{}\n{}\n{}", uri.toString(), response, ex.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException ignored) {
LOGGER.trace("IOException", ignored);
}
}
return results;
}
public static String post(String url, String payload) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
// httpPost.addHeader("Cookie", "rememberMe=" + Base64.getEncoder().encodeToString(data));
HttpEntity httpEntity = new StringEntity(payload, "application/x-www-form-urlencoded", "utf-8");
httpPost.setEntity(httpEntity);
try {
HttpClientBuilder httpClientBuilder = HttpClients
.custom()
// .setProxy(new HttpHost("127.0.0.1", 8080))
.disableRedirectHandling()
// .disableCookieManagement()
;
if (url.startsWith("https://")) {
httpClientBuilder.setSSLSocketFactory(sslsf);
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = httpClientBuilder.build();
response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public SAMLDocumentHolder extractResponse(CloseableHttpResponse response, String realmPublicKey) throws IOException {
assertThat(response, statusCodeIsHC(Response.Status.OK));
String responsePage = EntityUtils.toString(response.getEntity(), "UTF-8");
response.close();
return extractSamlResponseFromForm(responsePage);
}
protected void closeHttpConnections() {
for (CloseableHttpResponse response : httpResponses) {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOGGER.error("Could not close http connection", e);
}
}
}
httpResponses.clear();
}
private void prepareSelf() throws IOException {
String destLink = getDestLink();
CloseableHttpResponse response = connection.request(destLink);
int code = ResponseUtil.getHttpCode(response);
if (code != 200) {
System.out.println("failed to init " + destLink);
System.out.println("reason: " + ResponseUtil.getDetails(response));
}
try {
Header header = response.getFirstHeader(KEY_MSG_CREATE);
contextMap.put(KEY_MSG_CREATE, header.getValue());
header = response.getFirstHeader(KEY_MSG_CREATE_ID);
contextMap.put(KEY_MSG_CREATE_ID, header.getValue());
header = response.getFirstHeader(KEY_MSG_PULL);
if (header != null) {
contextMap.put(KEY_MSG_PULL, header.getValue());
}
header = response.getFirstHeader(KEY_MSG_PUSH);
if (header != null) {
contextMap.put(KEY_MSG_PUSH, header.getValue());
}
header = response.getFirstHeader(KEY_MSG_PULL_SUB);
if (header != null) {
contextMap.put(KEY_MSG_PULL_SUB, header.getValue());
}
header = response.getFirstHeader(KEY_MSG_PUSH_SUB);
if (header != null) {
contextMap.put(KEY_MSG_PUSH_SUB, header.getValue());
}
} finally {
response.close();
}
}
/**
* HTTP Post 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doPost(String url, Map<String, String> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
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));
}
}
}
HttpPost httpPost = new HttpPost(url);
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.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 post 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);
}
}
public static void patch(String REST_URI,
String did,
String accesskey,
String secretkey,
String sidpid,
Long startdate,
Long enddate,
Integer version,
String status,
String notes,
String policy) throws Exception
{
System.out.println("Patch policy test");
System.out.println("******************************************");
String apiversion = "2.0";
// Make API rest call and get response from the server
String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid;
System.out.println("\nCalling update @ " + resourceLoc);
PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest();
pfpr.setStartDate(startdate);
if (enddate != null)
pfpr.setEndDate(enddate);
pfpr.setVersion(version);
pfpr.setStatus(status);
pfpr.setNotes(notes);
pfpr.setPolicy(policy);
ObjectWriter ow = new ObjectMapper().writer();
String json = ow.writeValueAsString(pfpr);
ContentType mimetype = ContentType.create("application/merge-patch+json");
StringEntity body = new StringEntity(json, mimetype);
String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
String contentSHA = common.calculateSha256(json);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch(resourceLoc);
httpPatch.setEntity(body);
String requestToHmac = httpPatch.getMethod() + "\n"
+ contentSHA + "\n"
+ mimetype.getMimeType() + "\n"
+ currentDate + "\n"
+ apiversion + "\n"
+ httpPatch.getURI().getPath();
String hmac = common.calculateHMAC(secretkey, requestToHmac);
httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
httpPatch.addHeader("strongkey-content-sha256", contentSHA);
httpPatch.addHeader("Content-Type", mimetype.getMimeType());
httpPatch.addHeader("Date", currentDate);
httpPatch.addHeader("strongkey-api-version", apiversion);
CloseableHttpResponse response = httpclient.execute(httpPatch);
String result;
try {
StatusLine responseStatusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
switch (responseStatusLine.getStatusCode()) {
case 200:
break;
case 401:
System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed");
return;
case 404:
System.out.println("Error during patch fido policy : 404 Resource not found");
return;
case 400:
case 500:
default:
System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result);
return;
}
} finally {
response.close();
}
System.out.println(" Response : " + result);
System.out.println("\nPatch policy test complete.");
System.out.println("******************************************");
}
@Override
public void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions,
List<SignalFxProtocolBuffers.PointValue> datumPoints)
throws SignalFxMetricsException {
if (datumPoints.isEmpty()) {
return;
}
List<NameValuePair> params = Lists.newArrayList();
params.add(new BasicNameValuePair("orgid", orgId));
params.add(new BasicNameValuePair("metric_type", metricType));
params.add(new BasicNameValuePair("metric", metric));
// Each dimension is added as a param in the form of "sfxdim_DIMNAME"
for (Map.Entry<String,String> entry : dimensions.entrySet()) {
params.add(new BasicNameValuePair("sfxdim_" + entry.getKey(), entry.getValue()));
}
try {
CloseableHttpResponse resp = null;
try {
resp = postToEndpoint(auth,
new InputStreamEntity(
new ProtocolBufferStreamingInputStream<SignalFxProtocolBuffers.PointValue>(
datumPoints.iterator()), PROTO_TYPE),
"/v1/backfill?" + URLEncodedUtils.format(params, StandardCharsets.UTF_8),
false);
int code = resp.getStatusLine().getStatusCode();
if (code != HttpStatus.SC_OK) {
throw new SignalFxMetricsException("Invalid status code " + code);
}
} finally {
if (resp != null) {
resp.close();
}
}
} catch (IOException e) {
throw new SignalFxMetricsException("Exception posting to backfillDataPoints", e);
}
}
public <T> T executeAndTransform(ResultExtractor<T> resultTransformer, List<Step> steps) {
CloseableHttpResponse currentResponse = null;
URI currentUri = URI.create("about:blank");
strategy.setRedirectable(true);
try (CloseableHttpClient client = createHttpClientBuilderInstance().setRedirectStrategy(strategy).build()) {
for (int i = 0; i < steps.size(); i ++) {
Step s = steps.get(i);
LOG.infof("Running step %d: %s", i, s.getClass());
CloseableHttpResponse origResponse = currentResponse;
HttpUriRequest request = s.perform(client, currentUri, origResponse, context);
if (request == null) {
LOG.info("Last step returned no request, continuing with next step.");
continue;
}
// Setting of follow redirects has to be set before executing the final request of the current step
if (i < steps.size() - 1 && steps.get(i + 1) instanceof DoNotFollowRedirectStep) {
LOG.debugf("Disabling following redirects");
strategy.setRedirectable(false);
i++;
} else {
strategy.setRedirectable(true);
}
LOG.infof("Executing HTTP request to %s", request.getURI());
currentResponse = client.execute(request, context);
currentUri = request.getURI();
List<URI> locations = context.getRedirectLocations();
if (locations != null && ! locations.isEmpty()) {
currentUri = locations.get(locations.size() - 1);
}
LOG.infof("Landed to %s", currentUri);
if (currentResponse != origResponse && origResponse != null) {
origResponse.close();
}
}
LOG.info("Going to extract response");
return resultTransformer.extract(currentResponse);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static void find(CloseableHttpClient httpclient, WSSearchOptions wsso) throws Exception {
System.out.println("find");
//CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/search/find");
httppost.addHeader(new BasicHeader("Accept", "application/json"));
//ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
ObjectMapper mapper = new ObjectMapper();
ObjectWriter ow = mapper.writer();
String jsonStr = ow.writeValueAsString(wsso);
System.out.println(jsonStr);
StringEntity entity = new StringEntity(jsonStr, ContentType.create("application/json", Consts.UTF_8));
httppost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
System.out.println("HTTPstatus code: "+ code);
if (code == HttpStatus.SC_OK) {
} else {
//log.warn("status code is invalid: {}", code);
System.err.println("status code is invalid: "+ code);
throw new Exception(response.getStatusLine().getReasonPhrase());
}
try {
HttpEntity rent = response.getEntity();
if (rent != null) {
String respoBody = EntityUtils.toString(rent, "UTF-8");
System.out.println(respoBody);
//JSON from String to Object
//WSSearchResult obj = mapper.readValue(respoBody, WSSearchResult.class);
//System.out.println(ow.writeValueAsString(obj) );
}
} finally {
response.close();
}
}