@Override protected DescribeBinlogFileResult processResult(HttpResponse response) throws Exception { String result = EntityUtils.toString(response.getEntity()); DescribeBinlogFileResult describeBinlogFileResult = JSONObject.parseObject(result, new TypeReference<DescribeBinlogFileResult>() { }); return describeBinlogFileResult; } }
private void checkHttpResponseStatus(HttpResponse response) { if (response.getStatusLine().getStatusCode() == 200) { return; } StatusLine status = response.getStatusLine(); String message = ""; try { message = EntityUtils.toString(response.getEntity()); } catch (IOException e) { //ignore } throw new ApolloOpenApiException(status.getStatusCode(), status.getReasonPhrase(), message); }
public List<OpenEnvClusterDTO> getEnvClusterInfo(String appId) { checkNotEmpty(appId, "App id"); String path = String.format("apps/%s/envclusters", escapePath(appId)); try (CloseableHttpResponse response = get(path)) { return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_ENV_CLUSTER_DTO_LIST_TYPE); } catch (Throwable ex) { throw new RuntimeException(String.format("Load env cluster information for appId: %s failed", appId), ex); } } }
private String getHttpResponse(String fullUrl) throws IOException { HttpUriRequest req = new HttpGet(fullUrl); for (int numTries = 0;; numTries++) { try (CloseableHttpResponse response = this.httpClient.execute(req)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { throw new IOException( String.format("status code: %d, reason: %s", statusCode, response.getStatusLine().getReasonPhrase())); } return EntityUtils.toString(response.getEntity()); } catch (IOException e) { String errMsg = "Unable to get or parse HTTP response for " + fullUrl; if (numTries >= this.maxNumTries) { throw new IOException (errMsg, e); } long backOffSec = (numTries + 1) * 2; log.error(errMsg + ", will retry in " + backOffSec + " sec", e); try { Thread.sleep(TimeUnit.SECONDS.toMillis(backOffSec)); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } } }
private boolean httpGet(StringBuilder postAddr) { boolean ret = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpGet request = new HttpGet(postAddr.toString()); response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { LOG.info(EntityUtils.toString(entity)); } EntityUtils.consume(entity); ret = true; } catch (Exception e) { LOG.error("Exception when sending http request to ali monitor", e); } finally { try { if (response != null) response.close(); httpClient.close(); } catch (Exception e) { LOG.error("Exception when closing httpclient", e); } } return ret; }
/** * Default implementation where any status code equal to or greater than 400 is regarded as a failure. * {@inheritDoc} * @see org.apache.gobblin.writer.http.HttpWriterDecoration#processResponse(org.apache.http.HttpResponse) */ @Override public void processResponse(CloseableHttpResponse response) throws IOException, UnexpectedResponseException { if (response.getStatusLine().getStatusCode() >= 400) { if (response.getEntity() != null) { throw new RuntimeException("Failed. " + EntityUtils.toString(response.getEntity()) + " , response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE)); } throw new RuntimeException("Failed. Response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE)); } }
private String getHttpResponse(String url) { DefaultHttpClient client = new DefaultHttpClient(); String msg = null; int retry_times = 0; while (msg == null && retry_times < HTTP_RETRY) { retry_times++; 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={}", retry_times, e); } finally { request.releaseConnection(); } } return msg; }
@Test public void elasticsearchVersion() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:5.6.12")) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); String responseAsString = EntityUtils.toString(response.getEntity()); assertThat(responseAsString, containsString("5.6.12")); } }
@Test public void matches_shouldMatchPostBody() throws Exception { final String expectedText = "some post body text"; requestMatcherBuilder.postBody( actualPostBody -> EntityUtils.toString(actualPostBody).equals(expectedText)); HttpPut match = new HttpPut("example.com"); match.setEntity(new StringEntity(expectedText)); HttpPost noMatch = new HttpPost("example.com"); noMatch.setEntity(new StringEntity("some text that does not match")); assertThat(requestMatcherBuilder.matches(new HttpGet("example.com"))).isFalse(); assertThat(requestMatcherBuilder.matches(noMatch)).isFalse(); assertThat(requestMatcherBuilder.matches(match)).isTrue(); } }
/** * @param response The http response to verify. * @return null on failure or the response string if return code is in 200 range */ @Override public String handleResponse(final HttpResponse response) throws IOException { int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String entityString = (entity != null ? EntityUtils.toString(entity) : null); if (status >= 200 && status < 300) { return entityString; } else { LOG.error("Got unexpected response code {}; entity: {}", status, entityString); return null; } } }
.setSocketTimeout(timeout) .build(); HttpGet httpGet = new HttpGet(uri); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config); CloseableHttpResponse response = httpclient.execute(httpGet, context); try { int statusCode = response.getStatusLine().getStatusCode(); long end = System.currentTimeMillis(); long cost = end - start; return EntityUtils.toByteArray(response.getEntity()); } else { String errorMsg = EntityUtils.toString(response.getEntity()); throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg);
@Test public void jsp() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { try (CloseableHttpResponse res = hc.execute(new HttpGet(server().uri("/jsp/index.jsp")))) { assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK"); assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue()) .startsWith("text/html"); final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity())) .replaceAll(""); assertThat(actualContent).isEqualTo( "<html><body>" + "<p>Hello, Armerian World!</p>" + "<p>Have you heard about the class 'org.slf4j.Logger'?</p>" + "<p>Context path: </p>" + // ROOT context path "<p>Request URI: /index.jsp</p>" + "<p>Scheme: http</p>" + "</body></html>"); } } }
private void processSingleRequestResponse(CloseableHttpResponse response) throws IOException, UnexpectedResponseException { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 400) { return; } String entityStr = EntityUtils.toString(response.getEntity()); if (statusCode == 400 && Operation.INSERT_ONLY_NOT_EXIST.equals(operation) && entityStr != null) { //Ignore if it's duplicate entry error code JsonArray jsonArray = new JsonParser().parse(entityStr).getAsJsonArray(); JsonObject jsonObject = jsonArray.get(0).getAsJsonObject(); if (isDuplicate(jsonObject, statusCode)) { return; } } throw new RuntimeException("Failed due to " + entityStr + " (Detail: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )"); }
@Override public String call() throws Exception { try { if ( log.isBasic() ) { log.logBasic( BaseMessages.getString( PKG, "PurRepositoryConnector.SessionService.Start" ) ); } CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( username, password ); provider.setCredentials( AuthScope.ANY, credentials ); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider( provider ).build(); HttpGet method = new HttpGet( repositoryMeta.getRepositoryLocation().getUrl() + "/api/session/userName" ); if ( StringUtils.isNotBlank( System.getProperty( "pentaho.repository.client.attemptTrust" ) ) ) { method.addHeader( TRUST_USER, username ); } HttpResponse response = client.execute( method ); if ( log.isBasic() ) { log.logBasic( BaseMessages.getString( PKG, "PurRepositoryConnector.SessionService.Sync" ) ); //$NON-NLS-1$ } return EntityUtils.toString( response.getEntity() ); } catch ( Exception e ) { if ( log.isError() ) { log.logError( BaseMessages.getString( PKG, "PurRepositoryConnector.Error.EnableToGetUser" ), e ); } return null; } } } );
private boolean httpPost(String url, String msg) { boolean ret = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpPost request = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("name", monitorName)); nvps.add(new BasicNameValuePair("msg", msg)); request.setEntity(new UrlEncodedFormEntity(nvps)); response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { LOG.info(EntityUtils.toString(entity)); } EntityUtils.consume(entity); ret = true; } catch (Exception e) { LOG.error("Exception when sending http request to ali monitor", e); } finally { try { if (response != null) response.close(); httpClient.close(); } catch (Exception e) { LOG.error("Exception when closing httpclient", e); } } return ret; }
@Test public void elasticsearchDefaultTest() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer() .withEnv("foo", "bar") // dummy env for compiler checking correct generics usage ) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString(ELASTICSEARCH_DEFAULT_VERSION)); // The default image is running with the features under Elastic License response = getClient(container).performRequest(new Request("GET", "/_xpack/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); // For now we test that we have the monitoring feature available assertThat(EntityUtils.toString(response.getEntity()), containsString("monitoring")); } }
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { final StatusLine statusLine = response.getStatusLine(); final HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8); }
.setSocketTimeout(timeout) .build(); httpGet = new HttpGet(uri); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config); response = httpclient.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { return EntityUtils.toString(response.getEntity()); } else { String errorMsg = EntityUtils.toString(response.getEntity()); throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg);
@Test public void japanesePath() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { try (CloseableHttpResponse res = hc.execute(new HttpGet( server().uri("/jsp/" + URLEncoder.encode("日本語", "UTF-8") + "/index.jsp")))) { assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK"); assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue()) .startsWith("text/html"); final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity())) .replaceAll(""); assertThat(actualContent).isEqualTo( "<html><body>" + "<p>Hello, Armerian World!</p>" + "<p>Have you heard about the class 'org.slf4j.Logger'?</p>" + "<p>Context path: </p>" + // ROOT context path "<p>Request URI: /%E6%97%A5%E6%9C%AC%E8%AA%9E/index.jsp</p>" + "<p>Servlet Path: /日本語/index.jsp</p>" + "</body></html>"); } } }