Java Code Examples for org.apache.http.client.methods.CloseableHttpResponse#close()

The following examples show how to use org.apache.http.client.methods.CloseableHttpResponse#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 7 votes vote down vote up
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();
}
 
Example 2
Source File: Discord.java    From Rails with GNU General Public License v2.0 7 votes vote down vote up
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);
    }
}
 
Example 3
Source File: NomadApiClient.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 4
Source File: AutoOnboardPinotMetricsUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: HttpClientService.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
/**
 * 执行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;
}
 
Example 6
Source File: RestMessageContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
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();
   }
}
 
Example 7
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 8
Source File: SamlClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: HttpUtil.java    From learnjavabug with MIT License 5 votes vote down vote up
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;
  }
 
Example 10
Source File: SimpleHttpProvider.java    From streams with Apache License 2.0 5 votes vote down vote up
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;
  }
 
Example 11
Source File: BaseSpringDmnRestTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void closeResponse(CloseableHttpResponse response) {
    if (response != null) {
        try {
            response.close();
        } catch (IOException e) {
            throw new AssertionError("Could not close http connection", e);
        }
    }
}
 
Example 12
Source File: BounceProxyShutdownReporter.java    From joynr with Apache License 2.0 5 votes vote down vote up
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();
            }
        }
    }
 
Example 13
Source File: HttpService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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();
   }
}
 
Example 14
Source File: BaseSpringDmnRestTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 15
Source File: HttpClientHandler.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 16
Source File: AbstractHttpDataPointProtobufReceiverConnection.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 17
Source File: SamlClient.java    From keycloak with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 18
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
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("******************************************");
}
 
Example 19
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
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();
		}
	}
 
Example 20
Source File: HttpTookit.java    From lightconf with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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);
    }
}