org.apache.http.client.utils.HttpClientUtils Java Examples

The following examples show how to use org.apache.http.client.utils.HttpClientUtils. 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: HttpUtil.java    From easy_javadoc with Apache License 2.0 6 votes vote down vote up
public static String get(String url) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    String result = null;
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).build());
        response = httpclient.execute(httpGet);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        LOGGER.warn("请求" + url + "异常", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
    return result;
}
 
Example #2
Source File: DocTestUtils.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
static boolean isResponseContentValid(String url) {
    if ("true".equals(System.getProperty("bash.skipUrls", "false"))) {
        return true;
    }

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {
        CloseableHttpResponse response = httpClient.execute(new HttpOptions(url));

        Assert.assertTrue("Expected response content for " + url, 404 != response.getStatusLine().getStatusCode());

        String content = EntityUtils.toString(response.getEntity());
        return !content.contains("No matches for");
    } catch (Exception e) {
        return false;
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }
}
 
Example #3
Source File: RawHostedIT.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void contentTypeDetectedFromContent() throws Exception {

  HttpEntity textEntity = new StringEntity("test");
  rawClient.put("path/to/content", textEntity);
  HttpResponse response = rawClient.get("path/to/content");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_PLAIN));
  HttpClientUtils.closeQuietly(response);

  HttpEntity htmlEntity = new StringEntity("<html>...</html>");
  rawClient.put("path/to/content", htmlEntity);
  response = rawClient.get("path/to/content");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_HTML));
  HttpClientUtils.closeQuietly(response);

  // turn off strict validation so we can test falling back to declared content-type
  Configuration hostedConfig = repositoryManager.get(HOSTED_REPO).getConfiguration().copy();
  hostedConfig.attributes(STORAGE).set(STRICT_CONTENT_TYPE_VALIDATION, false);
  repositoryManager.update(hostedConfig);

  HttpEntity jsonEntity = new StringEntity("", ContentType.APPLICATION_JSON);
  rawClient.put("path/to/content", jsonEntity);
  response = rawClient.get("path/to/content");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.APPLICATION_JSON));
  HttpClientUtils.closeQuietly(response);
}
 
Example #4
Source File: ExecutionNodeTaskDispatcherImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
@Inject
public ExecutionNodeTaskDispatcherImpl(@Named("connector.max.connections") Integer maxConnections, @Named("connector.max.connections.per.route") Integer maxConnectionsPerRoute,
                                       @Named("connector.connection.timeout") Integer connectionTimeout, @Named("connector.socket.timeout") Integer socketTimeOut,
                                       MetricsClient metricsClient) {
    RequestConfig clientConfig = RequestConfig.custom()
            .setConnectTimeout((connectionTimeout).intValue())
            .setSocketTimeout((socketTimeOut).intValue())
            .setConnectionRequestTimeout((socketTimeOut).intValue())
            .build();
    PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
    syncConnectionManager.setMaxTotal(maxConnections);
    syncConnectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager)
            .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        HttpClientUtils.closeQuietly(closeableHttpClient);
    }));
    this.metricsClient = metricsClient;
}
 
Example #5
Source File: EventProxyConnector.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public void submitScheduledEvent(String name, Object data, String correlationId,String eventSource, Long triggerTime) {
    final String eventType = data.getClass().getName();
    if (eventSource == null) {
        eventSource = EXTERNAL;
    }
    final EventData eventData = new EventData(name, eventType, (String) data, eventSource);
    CloseableHttpResponse httpResponse = null;
    try {
        if(triggerTime != null) {
            httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId&triggerTime=" + triggerTime);
        } else {
            //this block is used by flux to trigger the event when the time has arrived, send the data as plain string without serializing,
            // as the data is already in serialized form (in ScheduledEvents table the data stored in serialized form)
            httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
    }
}
 
Example #6
Source File: EventProxyConnector.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public void submitEvent(String name, Object data, String correlationId, String eventSource) {
    final String eventType = data.getClass().getName();
    if (eventSource == null) {
        eventSource = EXTERNAL;
    }
    CloseableHttpResponse httpResponse = null;
    try {
        final EventData eventData = new EventData(name, eventType, (String) data, eventSource);
        httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
    }
}
 
Example #7
Source File: FluxRuntimeConnectorHttpImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public void submitEventUpdate(String name, Object data, String correlationId,String eventSource) {
    final String eventType = data.getClass().getName();
    if (eventSource == null) {
        eventSource = EXTERNAL;
    }
    CloseableHttpResponse httpResponse = null;
    try {
        final EventData eventData = new EventData(name, eventType, objectMapper.writeValueAsString(data), eventSource);
        httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/eventupdate");

    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
    }
}
 
Example #8
Source File: FluxRuntimeConnectorHttpImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public void submitEvent(String name, Object data, String correlationId, String eventSource) {
    final String eventType = data.getClass().getName();
    if (eventSource == null) {
        eventSource = EXTERNAL;
    }
    CloseableHttpResponse httpResponse = null;
    try {
        final EventData eventData = new EventData(name, eventType, objectMapper.writeValueAsString(data), eventSource);
        httpResponse = postOverHttp(eventData, "/" + correlationId + "/context/events?searchField=correlationId");
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
    }
}
 
Example #9
Source File: FluxRuntimeConnectorHttpImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
@Override
public void submitNewWorkflow(StateMachineDefinition stateMachineDef) {
    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = postOverHttp(stateMachineDef, "");
        if(logger.isDebugEnabled()) {
            try {
                logger.debug("Flux returned response: {}", EntityUtils.toString(httpResponse.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
    }
}
 
Example #10
Source File: FluxRuntimeConnectorHttpImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
public FluxRuntimeConnectorHttpImpl(Long connectionTimeout, Long socketTimeout, String fluxEndpoint, ObjectMapper objectMapper,
                                    MetricRegistry metricRegistry) {
    this.fluxEndpoint = fluxEndpoint;
    this.objectMapper = objectMapper;
    RequestConfig clientConfig = RequestConfig.custom()
        .setConnectTimeout((connectionTimeout).intValue())
        .setSocketTimeout((socketTimeout).intValue())
        .setConnectionRequestTimeout((socketTimeout).intValue())
        .build();
    PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
    syncConnectionManager.setMaxTotal(MAX_TOTAL);
    syncConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);

    closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager)
        .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        HttpClientUtils.closeQuietly(closeableHttpClient);
    }));
    this.metricRegistry = metricRegistry;
}
 
Example #11
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This method executes the given {@link ApacheCloudStackRequest}.
 * It will return the response as a plain {@link String}.
 * You should have in mind that if the parameter 'response' is not set, the default is 'XML'.
 */
public String executeRequest(ApacheCloudStackRequest request) {
    boolean isSecretKeyApiKeyAuthenticationMechanism = StringUtils.isNotBlank(this.apacheCloudStackUser.getApiKey());
    String urlRequest = createApacheCloudStackApiUrlRequest(request, isSecretKeyApiKeyAuthenticationMechanism);
    LOGGER.debug(String.format("Executing request[%s].", urlRequest));
    CloseableHttpClient httpClient = createHttpClient();
    HttpContext httpContext = createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(httpClient, isSecretKeyApiKeyAuthenticationMechanism);
    try {
        return executeRequestGetResponseAsString(urlRequest, httpClient, httpContext);
    } finally {
        if (!isSecretKeyApiKeyAuthenticationMechanism) {
            executeUserLogout(httpClient, httpContext);
        }
        HttpClientUtils.closeQuietly(httpClient);
    }
}
 
Example #12
Source File: RestUtils.java    From video-recorder-java with MIT License 6 votes vote down vote up
public static String sendRecordingRequest(final String url) {
    CloseableHttpResponse response = null;
    try (final CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final HttpGet get = new HttpGet(url);
        response = client.execute(get);
        HttpEntity content = response.getEntity();
        String message = EntityUtils.toString(content);
        LOGGER.info("Response: " + message);
        return message;
    } catch (Exception ex) {
        LOGGER.severe("Request: " + ex);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return "";
}
 
Example #13
Source File: RestUtils.java    From video-recorder-java with MIT License 6 votes vote down vote up
public static String sendRecordingRequest(final String url) {
    CloseableHttpResponse response = null;
    try (final CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final HttpGet get = new HttpGet(url);
        response = client.execute(get);
        HttpEntity content = response.getEntity();
        String message = EntityUtils.toString(content);
        LOGGER.info("Response: " + message);
        return message;
    } catch (Exception ex) {
        LOGGER.severe("Request: " + ex);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return "";
}
 
Example #14
Source File: AsyncHttpClient.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
        public void completed(HttpResponse httpResponse) {
            try {
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK == statusCode) {
                     String response = EntityUtils.toString(httpResponse.getEntity());
//                     logger.info(response);
                     synchronized (object) {
                         result.add(response);
                     }
                }
            } catch (IOException e){
                logger.info("network io exception",e);
            } finally {
                latch.countDown();
                HttpClientUtils.closeQuietly(httpResponse);
            }
        }
 
Example #15
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Optional<SnapshotItem> fetchLatest(final ContentSpecifier spec) throws IOException {
  AptFacet aptFacet = getRepository().facet(AptFacet.class);
  ProxyFacet proxyFacet = facet(ProxyFacet.class);
  HttpClientFacet httpClientFacet = facet(HttpClientFacet.class);
  HttpClient httpClient = httpClientFacet.getHttpClient();
  CacheController cacheController = cacheControllerHolder.getMetadataCacheController();
  CacheInfo cacheInfo = cacheController.current();
  Content oldVersion = aptFacet.get(spec.path);

  URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path);
  HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri);

  HttpResponse response = httpClient.execute(getRequest);
  StatusLine status = response.getStatusLine();

  if (status.getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    Content fetchedContent = new Content(new HttpEntityPayload(response, entity));
    AttributesMap contentAttrs = fetchedContent.getAttributes();
    contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED));
    contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG));
    contentAttrs.set(CacheInfo.class, cacheInfo);
    Content storedContent = getAptFacet().put(spec.path, fetchedContent);
    return Optional.of(new SnapshotItem(spec, storedContent));
  }

  try {
    if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
      checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri);
      doIndicateVerified(oldVersion, cacheInfo, spec.path);
      return Optional.of(new SnapshotItem(spec, oldVersion));
    }
    throwProxyExceptionForStatus(response);
  }
  finally {
    HttpClientUtils.closeQuietly(response);
  }

  return Optional.empty();
}
 
Example #16
Source File: SharedHttpClientSessionManager.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param httpClient The httpClient to use for remote/service calls.
 */
@Override
public void setHttpClient(HttpClient httpClient) {
	synchronized (this) {
		this.httpClient = Objects.requireNonNull(httpClient, "HTTP Client cannot be null");
		// If they set a client, we need to check whether we need to
		// close any existing dependentClient
		CloseableHttpClient toCloseDependentClient = dependentClient;
		dependentClient = null;
		if (toCloseDependentClient != null) {
			HttpClientUtils.closeQuietly(toCloseDependentClient);
		}
	}
}
 
Example #17
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void mayThrowBypassHttpErrorException(final HttpResponse httpResponse) {
  final StatusLine status = httpResponse.getStatusLine();
  if (httpResponse.containsHeader(BYPASS_HTTP_ERRORS_HEADER_NAME)) {
    log.debug("Bypass http error: {}", status);
    ListMultimap<String, String> headers = ArrayListMultimap.create();
    headers.put(BYPASS_HTTP_ERRORS_HEADER_NAME, BYPASS_HTTP_ERRORS_HEADER_VALUE);
    HttpClientUtils.closeQuietly(httpResponse);
    throw new BypassHttpErrorException(status.getStatusCode(), status.getReasonPhrase(), headers);
  }
}
 
Example #18
Source File: HttpClientRequesterImpl.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execute(HttpUriRequest request, HttpClientContext context, RequestFunction<T> func)
        throws IOException, UnauthorizedAccessException {
    HttpClient client = HttpClientBuilder.create().build();
    try {
        return func.run(client.execute(request, context));
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}
 
Example #19
Source File: HttpClientRequesterImpl.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execute(HttpUriRequest request, HttpClientContext context, CredentialsProvider provider,
        RequestFunction<T> func)
        throws IOException, UnauthorizedAccessException {
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    try {
        return func.run(client.execute(request, context));
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}
 
Example #20
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Calling close will force the method to close, and will
 * force any open stream to terminate. If the session is local,
 * Then that too will be closed.
 */
public synchronized void close() {
  if (closed)
    return; // recursive calls ok
  closed = true; // mark as closed to prevent recursive calls
  if (methodstream != null) {
    try {
      this.methodstream.close(); // May recursr
    } catch (IOException ioe) {
      /* failure is ok */}
    this.methodstream = null;
  }
  // Force release underlying connection back to the connection manager
  if (this.lastresponse != null) {
    if (false) {
      try {
        try {
          // Attempt to keep connection alive by consuming its remaining content
          EntityUtils.consume(this.lastresponse.getEntity());
        } finally {
          HttpClientUtils.closeQuietly(this.lastresponse); // Paranoia
        }
      } catch (IOException ignore) {
        /* ignore */}
    } else
      HttpClientUtils.closeQuietly(this.lastresponse);
    this.lastresponse = null;
  }
  if (session != null) {
    session.removeMethod(this);
    if (localsession) {
      session.close();
      session = null;
    }
  }
  this.lastrequest = null;
}
 
Example #21
Source File: AbstractRestServerTest.java    From vxquery with Apache License 2.0 5 votes vote down vote up
/**
 * Submit a {@link QueryRequest} and fetth the resulting
 * {@link AsyncQueryResponse}
 *
 * @param uri
 *            uri of the GET request
 * @param accepts
 *            application/json | application/xml
 * @param method
 *            Http Method to be used to send the request
 * @return Response received for the query request
 * @throws Exception
 */
protected static <T> T getQuerySuccessResponse(URI uri, String accepts, Class<T> type, String method)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build();

    try {
        HttpUriRequest request = getRequest(uri, method);

        if (accepts != null) {
            request.setHeader(HttpHeaders.ACCEPT, accepts);
        }

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {
            Assert.assertEquals(HttpResponseStatus.OK.code(), httpResponse.getStatusLine().getStatusCode());
            if (accepts != null) {
                Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
            }

            HttpEntity entity = httpResponse.getEntity();
            Assert.assertNotNull(entity);

            String response = RestUtils.readEntity(entity);
            return RestUtils.mapEntity(response, type, accepts);
        }
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }
}
 
Example #22
Source File: AbstractRestServerTest.java    From vxquery with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch the {@link QueryResultResponse} from query result endpoint once the
 * corresponding {@link QueryResultRequest} is given.
 *
 * @param resultRequest
 *            {@link QueryResultRequest}
 * @param accepts
 *            expected
 *
 *            <pre>
 *            Accepts
 *            </pre>
 *
 *            header in responses
 * @param method
 *            Http Method to be used to send the request
 * @return query result response received
 * @throws Exception
 */
protected static QueryResultResponse getQueryResultResponse(QueryResultRequest resultRequest, String accepts,
        String method) throws Exception {
    URI uri = RestUtils.buildQueryResultURI(resultRequest, restIpAddress, restPort);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build();
    try {
        HttpUriRequest request = getRequest(uri, method);

        if (accepts != null) {
            request.setHeader(HttpHeaders.ACCEPT, accepts);
        }

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {
            if (accepts != null) {
                Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
            }
            Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpResponseStatus.OK.code());

            HttpEntity entity = httpResponse.getEntity();
            Assert.assertNotNull(entity);

            String response = RestUtils.readEntity(entity);
            return RestUtils.mapEntity(response, QueryResultResponse.class, accepts);
        }
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }
}
 
Example #23
Source File: ErrorResponseTest.java    From vxquery with Apache License 2.0 5 votes vote down vote up
private void runTest(URI uri, String accepts, int expectedStatusCode, String httpMethod) throws Exception {
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build();

    ErrorResponse errorResponse;
    try {
        HttpUriRequest request = getRequest(uri, httpMethod);
        if (accepts != null) {
            request.setHeader(HttpHeaders.ACCEPT, accepts);
        }

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {
            Assert.assertEquals(expectedStatusCode, httpResponse.getStatusLine().getStatusCode());
            if (accepts != null) {
                Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
            }

            HttpEntity entity = httpResponse.getEntity();
            Assert.assertNotNull(entity);

            String response = RestUtils.readEntity(entity);
            errorResponse = RestUtils.mapEntity(response, ErrorResponse.class, accepts);
        }
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }

    Assert.assertNotNull(errorResponse);
    Assert.assertNotNull(errorResponse.getError().getMessage());
    Assert.assertEquals(errorResponse.getError().getCode(), expectedStatusCode);
}
 
Example #24
Source File: ThriftConnection.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void close() throws IOException {
  if (httpClient != null && httpClientCreated) {
    HttpClientUtils.closeQuietly(httpClient);
  }
  isClosed = true;
}
 
Example #25
Source File: AsyncRequestWrapperImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private R instantiateResponse(final HttpResponse res) {
  R odataResponse;
  try {
    odataResponse = (R) ((AbstractODataRequest) odataRequest).getResponseTemplate().initFromEnclosedPart(res
        .getEntity().getContent());
  } catch (Exception e) {
    LOG.error("Error instantiating odata response", e);
    odataResponse = null;
  } finally {
    HttpClientUtils.closeQuietly(res);
  }
  return odataResponse;
}
 
Example #26
Source File: AbstractODataResponse.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public final ODataResponse initFromHttpResponse(final HttpResponse res) {
  try {
    this.payload = res.getEntity() == null ? null : res.getEntity().getContent();
    this.inputContent = null;
  } catch (final IllegalStateException | IOException e) {
    HttpClientUtils.closeQuietly(res);
    LOG.error("Error retrieving payload", e);
    throw new ODataRuntimeException(e);
  }
  for (Header header : res.getAllHeaders()) {
    final Collection<String> headerValues;
    if (headers.containsKey(header.getName())) {
      headerValues = headers.get(header.getName());
    } else {
      headerValues = new HashSet<>();
      headers.put(header.getName(), headerValues);
    }

    headerValues.add(header.getValue());
  }

  statusCode = res.getStatusLine().getStatusCode();
  statusMessage = res.getStatusLine().getReasonPhrase();

  hasBeenInitialized = true;
  return this;
}
 
Example #27
Source File: RestResult.java    From support-diagnostics with Apache License 2.0 5 votes vote down vote up
public RestResult(HttpResponse response, String url) {
    this.url = url;
    try{
        processCodes(response);
        responseString = EntityUtils.toString(response.getEntity());
    }
    catch (Exception e){
        logger.error( "Error Processing Response", e);
        throw new RuntimeException();
    }
    finally {
        HttpClientUtils.closeQuietly(response);
    }
}
 
Example #28
Source File: RestResult.java    From support-diagnostics with Apache License 2.0 5 votes vote down vote up
public RestResult(HttpResponse response, String fileName, String url) {

        this.url = url;

        // If the query got a success status stream the result immediately to the target file.
        // If not, the result should be small and contain diagnostic info so stgre it in the response string.
        File output = new File(fileName);
        if(output.exists()){
            FileUtils.deleteQuietly(output);
        }

        try(OutputStream out = new FileOutputStream(fileName)){
            processCodes(response);
            if (status == 200) {
                response.getEntity().writeTo(out);
            } else {
                responseString = EntityUtils.toString(response.getEntity());
                IOUtils.write(reason + SystemProperties.lineSeparator + responseString, out, Constants.UTF_8);
            }
        } catch (Exception e) {
            logger.error( "Error Streaming Response To OutputStream", e);
            throw new RuntimeException();
        }
        finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
 
Example #29
Source File: BintrayImpl.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse handleResponse(HttpResponse response) throws BintrayCallException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusNotOk(statusCode)) {
        BintrayCallException bce = new BintrayCallException(response);

        //We're using CloseableHttpClient so it's ok
        HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
        throw bce;
    }

    //Response entity might be null, 500 and 405 also give the html itself so skip it
    byte[] entity = new byte[0];
    if (response.getEntity() != null && statusCode != 500 && statusCode != 405) {
        try {
            entity = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (IOException | NullPointerException e) {
            //Null entity - Ignore
        } finally {
            HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
        }
    }

    HttpResponse newResponse = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(response.getStatusLine(),
            new HttpClientContext());
    newResponse.setEntity(new ByteArrayEntity(entity));
    newResponse.setHeaders(response.getAllHeaders());
    return newResponse;
}
 
Example #30
Source File: RawHostedIT.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void contentTypeDetectedFromPath() throws Exception {
  HttpEntity testEntity = new ByteArrayEntity(new byte[0]);

  rawClient.put("path/to/content.txt", testEntity);
  HttpResponse response = rawClient.get("path/to/content.txt");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_PLAIN));
  HttpClientUtils.closeQuietly(response);

  rawClient.put("path/to/content.html", testEntity);
  response = rawClient.get("path/to/content.html");
  MatcherAssert.assertThat(response.getFirstHeader("Content-Type").getValue(), Matchers.is(ContentTypes.TEXT_HTML));
  HttpClientUtils.closeQuietly(response);
}