Java Code Examples for org.apache.http.client.methods.HttpUriRequest#getURI()

The following examples show how to use org.apache.http.client.methods.HttpUriRequest#getURI() . 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: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpResponse execute(HttpUriRequest req, @Nullable Credentials auth) throws IOException {
   if (auth != null) {
      URI uri = req.getURI();
      AuthScope scope = new AuthScope(uri.getHost(), uri.getPort());

      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(scope, auth);

      HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(provider);

      return get().execute(req, context);
   }

   return execute(req);
}
 
Example 2
Source File: HttpStreamTools.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
public static InputStream streamContent(HttpInterface httpInterface, HttpUriRequest request) {
  CloseableHttpResponse response = null;
  boolean success = false;

  try {
    response = httpInterface.execute(request);
    int statusCode = response.getStatusLine().getStatusCode();

    if (!HttpClientTools.isSuccessWithContent(statusCode)) {
      throw new IOException("Invalid status code from " + request.getURI() + " URL: " + statusCode);
    }

    success = true;
    return response.getEntity().getContent();
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (response != null && !success) {
      ExceptionTools.closeWithWarnings(response);
    }
  }
}
 
Example 3
Source File: ZkRoutingDataWriter.java    From helix with Apache License 2.0 6 votes vote down vote up
protected boolean sendRequestToLeader(HttpUriRequest request, int expectedResponseCode) {
  try {
    HttpResponse response = _forwardHttpClient.execute(request);
    if (response.getStatusLine().getStatusCode() != expectedResponseCode) {
      HttpEntity respEntity = response.getEntity();
      String errorLog = "The forwarded request to leader has failed. Uri: " + request.getURI()
          + ". Error code: " + response.getStatusLine().getStatusCode() + " Current hostname: "
          + _myHostName;
      if (respEntity != null) {
        errorLog += " Response: " + EntityUtils.toString(respEntity);
      }
      LOG.error(errorLog);
      return false;
    }
  } catch (IOException e) {
    LOG.error(
        "The forwarded request to leader raised an exception. Uri: {} Current hostname: {} ",
        request.getURI(), _myHostName, e);
    return false;
  }
  return true;
}
 
Example 4
Source File: ApacheHttpAsyncClientAspect.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@OnBefore
public static @Nullable AsyncTraceEntry onBefore(ThreadContext context,
        @BindParameter @Nullable HttpUriRequest request,
        @BindParameter ParameterHolder<FutureCallback<HttpResponse>> callback) {
    if (request == null) {
        return null;
    }
    String method = request.getMethod();
    if (method == null) {
        method = "";
    } else {
        method += " ";
    }
    URI uriObj = request.getURI();
    String uri;
    if (uriObj == null) {
        uri = "";
    } else {
        uri = uriObj.toString();
    }
    AsyncTraceEntry asyncTraceEntry = context.startAsyncServiceCallEntry("HTTP",
            method + Uris.stripQueryString(uri),
            MessageSupplier.create("http client request: {}{}", method, uri), timerName);
    callback.set(createWrapper(context, callback, asyncTraceEntry));
    return asyncTraceEntry;
}
 
Example 5
Source File: AbstractODataRouteTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected String getRealRefServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpContext httpContext = new BasicHttpContext();
    httpclient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest)httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost)httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);

    return currentReq.getURI().isAbsolute() ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
}
 
Example 6
Source File: ImmersionHttpClient.java    From letv with Apache License 2.0 5 votes vote down vote up
private HttpResponse b0449щ0449щщ0449(HttpUriRequest httpUriRequest, Map map, int i) throws Exception {
    URI uri = httpUriRequest.getURI();
    String trim = uri.getHost() != null ? uri.getHost().trim() : "";
    if (trim.length() > 0) {
        httpUriRequest.setHeader("Host", trim);
    }
    if (map != null) {
        for (Object next : map.entrySet()) {
            if (((b04170417041704170417З + b0417ЗЗЗЗ0417) * b04170417041704170417З) % bЗ0417ЗЗЗ0417 != bЗЗЗЗЗ0417) {
                b04170417041704170417З = 81;
                bЗЗЗЗЗ0417 = 31;
            }
            Entry entry = (Entry) next;
            httpUriRequest.setHeader((String) entry.getKey(), (String) entry.getValue());
        }
    }
    Header[] allHeaders = httpUriRequest.getAllHeaders();
    Log.d(b043D043Dнн043Dн, "request URI [" + httpUriRequest.getURI() + "]");
    for (Object obj : allHeaders) {
        Log.d(b043D043Dнн043Dн, "request header [" + obj.toString() + "]");
    }
    HttpConnectionParams.setSoTimeout(this.bнн043Dн043Dн.getParams(), i);
    HttpResponse execute = this.bнн043Dн043Dн.execute(httpUriRequest);
    if (execute != null) {
        return execute;
    }
    throw new RuntimeException("Null response returned.");
}
 
Example 7
Source File: TracedHttpClient.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
public static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;

    final URI requestUri = request.getURI();
    if (requestUri.isAbsolute()) {
        target = URIUtils.extractHost(requestUri);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: "
                    + requestUri);
        }
    }
    return target;
}
 
Example 8
Source File: Olingo4IntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private String getRealServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpContext httpContext = new BasicHttpContext();
    httpclient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());

    return currentUrl;
}
 
Example 9
Source File: BeamSegmentUrlProvider.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
protected String fetchSegmentPlaylistUrl(HttpInterface httpInterface) throws IOException {
  if (streamSegmentPlaylistUrl != null) {
    return streamSegmentPlaylistUrl;
  }

  HttpUriRequest jsonRequest = new HttpGet("https://mixer.com/api/v1/channels/" + channelId + "/manifest.light2");
  JsonBrowser lightManifest = HttpClientTools.fetchResponseAsJson(httpInterface, jsonRequest);

  if (lightManifest == null) {
    throw new IllegalStateException("Did not find light manifest at " + jsonRequest.getURI());
  }

  HttpUriRequest manifestRequest = new HttpGet("https://mixer.com" + lightManifest.get("hlsSrc").text());
  List<ChannelStreamInfo> streams = loadChannelStreamsList(fetchResponseLines(httpInterface, manifestRequest,
      "mixer channel streams list"));

  if (streams.isEmpty()) {
    throw new IllegalStateException("No streams available on channel.");
  }

  ChannelStreamInfo stream = streams.get(0);

  log.debug("Chose stream with quality {} from url {}", stream.quality, stream.url);
  streamSegmentPlaylistUrl = stream.url;
  return streamSegmentPlaylistUrl;
}
 
Example 10
Source File: ErrorResponseException.java    From nomad-java-sdk with Mozilla Public License 2.0 5 votes vote down vote up
private ErrorResponseException(HttpUriRequest request,
                               String errorLocation,
                               String serverErrorMessage,
                               int serverErrorCode,
                               @Nullable String rawEntity) {

    super(
            request.getMethod() + " " + request.getURI()
                    + " resulted in error " + errorLocation + ": " + serverErrorMessage,
            rawEntity,
            null);
    this.serverErrorMessage = serverErrorMessage;
    this.serverErrorCode = serverErrorCode;
}
 
Example 11
Source File: NFHttpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
	// A null target may be acceptable if there is a default target.
	// Otherwise, the null target is detected in the director.
	HttpHost target = null;
	URI requestURI = request.getURI();
	if (requestURI.isAbsolute()) {
		target = URIUtils.extractHost(requestURI);
		if (target == null) {
			throw new ClientProtocolException(
					"URI does not specify a valid host name: " + requestURI);
		}
	}
	return target;
}
 
Example 12
Source File: BasicRestClient.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private void logRequestExecution(final HttpUriRequest request) {
    final URI uri = request.getURI();
    String query = uri.getQuery();
    query = query != null ? "?" + query : "";
    s_logger.debug("Executig " + request.getMethod() + " request on " + clientContext.getTargetHost() + uri.getPath() + query);
}
 
Example 13
Source File: AndroidHttpClient.java    From android-download-manager with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken)
		throws IOException {
	StringBuilder builder = new StringBuilder();

	builder.append("curl ");

	for (Header header : request.getAllHeaders()) {
		if (!logAuthToken
				&& (header.getName().equals("Authorization") || header
						.getName().equals("Cookie"))) {
			continue;
		}
		builder.append("--header \"");
		builder.append(header.toString().trim());
		builder.append("\" ");
	}

	URI uri = request.getURI();

	// If this is a wrapped request, use the URI from the original
	// request instead. getURI() on the wrapper seems to return a
	// relative URI. We want an absolute URI.
	if (request instanceof RequestWrapper) {
		HttpRequest original = ((RequestWrapper) request).getOriginal();
		if (original instanceof HttpUriRequest) {
			uri = ((HttpUriRequest) original).getURI();
		}
	}

	builder.append("\"");
	builder.append(uri);
	builder.append("\"");

	if (request instanceof HttpEntityEnclosingRequest) {
		HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
		HttpEntity entity = entityRequest.getEntity();
		if (entity != null && entity.isRepeatable()) {
			if (entity.getContentLength() < 1024) {
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				entity.writeTo(stream);
				String entityString = stream.toString();

				// TODO: Check the content type, too.
				builder.append(" --data-ascii \"").append(entityString)
						.append("\"");
			} else {
				builder.append(" [TOO MUCH DATA TO INCLUDE]");
			}
		}
	}

	return builder.toString();
}
 
Example 14
Source File: BasicRequest.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
private static HttpHost getHost(HttpUriRequest request) {
    URI uri = request.getURI();
    return new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
}
 
Example 15
Source File: HttpGetter.java    From commafeed with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param url
 *            the url to retrive
 * @param lastModified
 *            header we got last time we queried that url, or null
 * @param eTag
 *            header we got last time we queried that url, or null
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 * @throws NotModifiedException
 *             if the url hasn't changed since we asked for it last time
 */
public HttpResult getBinary(String url, String lastModified, String eTag, int timeout) throws ClientProtocolException, IOException,
		NotModifiedException {
	HttpResult result = null;
	long start = System.currentTimeMillis();

	CloseableHttpClient client = newClient(timeout);
	CloseableHttpResponse response = null;
	try {
		HttpGet httpget = new HttpGet(url);
		HttpClientContext context = HttpClientContext.create();

		httpget.addHeader(HttpHeaders.ACCEPT_LANGUAGE, ACCEPT_LANGUAGE);
		httpget.addHeader(HttpHeaders.PRAGMA, PRAGMA_NO_CACHE);
		httpget.addHeader(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
		httpget.addHeader(HttpHeaders.USER_AGENT, userAgent);

		if (lastModified != null) {
			httpget.addHeader(HttpHeaders.IF_MODIFIED_SINCE, lastModified);
		}
		if (eTag != null) {
			httpget.addHeader(HttpHeaders.IF_NONE_MATCH, eTag);
		}

		try {
			response = client.execute(httpget, context);
			int code = response.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_NOT_MODIFIED) {
				throw new NotModifiedException("'304 - not modified' http code received");
			} else if (code >= 300) {
				throw new HttpResponseException(code, "Server returned HTTP error code " + code);
			}

		} catch (HttpResponseException e) {
			if (e.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
				throw new NotModifiedException("'304 - not modified' http code received");
			} else {
				throw e;
			}
		}
		Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
		String lastModifiedHeaderValue = lastModifiedHeader == null ? null : StringUtils.trimToNull(lastModifiedHeader.getValue());
		if (lastModifiedHeaderValue != null && StringUtils.equals(lastModified, lastModifiedHeaderValue)) {
			throw new NotModifiedException("lastModifiedHeader is the same");
		}

		Header eTagHeader = response.getFirstHeader(HttpHeaders.ETAG);
		String eTagHeaderValue = eTagHeader == null ? null : StringUtils.trimToNull(eTagHeader.getValue());
		if (eTag != null && StringUtils.equals(eTag, eTagHeaderValue)) {
			throw new NotModifiedException("eTagHeader is the same");
		}

		HttpEntity entity = response.getEntity();
		byte[] content = null;
		String contentType = null;
		if (entity != null) {
			content = EntityUtils.toByteArray(entity);
			if (entity.getContentType() != null) {
				contentType = entity.getContentType().getValue();
			}
		}

		String urlAfterRedirect = url;
		if (context.getRequest() instanceof HttpUriRequest) {
			HttpUriRequest req = (HttpUriRequest) context.getRequest();
			HttpHost host = context.getTargetHost();
			urlAfterRedirect = req.getURI().isAbsolute() ? req.getURI().toString() : host.toURI() + req.getURI();
		}

		long duration = System.currentTimeMillis() - start;
		result = new HttpResult(content, contentType, lastModifiedHeaderValue, eTagHeaderValue, duration, urlAfterRedirect);
	} finally {
		IOUtils.closeQuietly(response);
		IOUtils.closeQuietly(client);
	}
	return result;
}
 
Example 16
Source File: AndroidHttpClient.java    From Alite with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header: request.getAllHeaders()) {
        if (!logAuthToken
                && (header.getName().equals("Authorization") ||
                    header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest =
                (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"")
                        .append(entityString)
                        .append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}
 
Example 17
Source File: AndroidHttpClient.java    From travelguide with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header: request.getAllHeaders()) {
        if (!logAuthToken
                && (header.getName().equals("Authorization") ||
                    header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest =
                (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"")
                        .append(entityString)
                        .append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}
 
Example 18
Source File: CommonsDataLoader.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected HttpHost getHttpHost(final HttpUriRequest httpRequest) {
	final URI uri = httpRequest.getURI();
	return new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
}
 
Example 19
Source File: MockHttpClientOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException, JAXBException
{
    LOGGER.debug("request = " + request);

    ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, HttpStatus.SC_OK, "Success");
    MockCloseableHttpResponse response = new MockCloseableHttpResponse(statusLine, false);

    // Find out which API's are being called and build an appropriate response.
    URI uri = request.getURI();
    if (request instanceof HttpGet)
    {
        if (uri.getPath().startsWith("/herd-app/rest/businessObjectData/"))
        {
            if (uri.getPath().endsWith("s3KeyPrefix"))
            {
                buildGetS3KeyPrefixResponse(response, uri);
            }
            else if (uri.getPath().endsWith("versions"))
            {
                buildGetBusinessObjectDataVersionsResponse(response, uri);
            }
            else if (uri.getPath().startsWith("/herd-app/rest/businessObjectData/upload/credential"))
            {
                getBusinessObjectDataUploadCredentialResponse(response, uri);
            }
            else
            {
                buildGetBusinessObjectDataResponse(response, uri);
            }
        }
        else if (uri.getPath().startsWith("/herd-app/rest/businessObjectDefinitions/"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION);
            buildGetBusinessObjectDefinitionResponse(response, uri);
        }
        else if (uri.getPath().startsWith("/herd-app/rest/storages/"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION_DURING_GET_STORAGE);
            buildGetStorageResponse(response, uri);
        }
        else if (uri.getPath().startsWith("/herd-app/rest/storageUnits/download/credential"))
        {
            getStorageUnitDownloadCredentialResponse(response, uri);
        }
    }
    else if (request instanceof HttpPost)
    {
        if (uri.getPath().startsWith("/herd-app/rest/businessObjectDataStorageFiles"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION_DURING_ADD_STORAGE_FILES);
            buildPostBusinessObjectDataStorageFilesResponse(response, uri);
        }
        else if (uri.getPath().equals("/herd-app/rest/businessObjectData"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION_DURING_REGISTER_BDATA);
            buildPostBusinessObjectDataResponse(response, uri);
        }
        else if (uri.getPath().equals("/herd-app/rest/businessObjectData/search"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION);
            buildSearchBusinessObjectDataResponse(response, uri);
        }
        else if (uri.getPath().startsWith("/herd-app/rest/businessObjectData/destroy"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION);
            buildPostBusinessObjectDataResponse(response, uri);
        }
    }
    else if (request instanceof HttpPut)
    {
        if (uri.getPath().startsWith("/herd-app/rest/businessObjectDataStatus/"))
        {
            checkHostname(request, HOSTNAME_THROW_IO_EXCEPTION_DURING_UPDATE_BDATA_STATUS);
            buildPutBusinessObjectDataStatusResponse(response, uri);
        }
    }

    // If requested, set response content to an invalid XML.
    if (HOSTNAME_RESPOND_WITH_STATUS_CODE_200_AND_INVALID_CONTENT.equals(request.getURI().getHost()))
    {
        response.setEntity(new StringEntity("invalid xml"));
    }

    LOGGER.debug("response = " + response);
    return response;
}
 
Example 20
Source File: BasicRestClient.java    From cosmic with Apache License 2.0 4 votes vote down vote up
private void logRequestExecution(final HttpUriRequest request) {
    final URI uri = request.getURI();
    String query = uri.getQuery();
    query = query != null ? "?" + query : "";
    s_logger.debug("Executig " + request.getMethod() + " request on " + clientContext.getTargetHost() + uri.getPath() + query);
}