Example usage for org.apache.http.client.methods HttpRequestBase setURI

List of usage examples for org.apache.http.client.methods HttpRequestBase setURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase setURI.

Prototype

public void setURI(final URI uri) 

Source Link

Usage

From source file:org.ballerinalang.composer.service.tryit.service.HttpTryItClient.java

/**
 * {@inheritDoc}/*from w w  w .j a  va2s .  co m*/
 */
@Override
public String execute() throws TryItException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpCoreContext localContext = new HttpCoreContext();
        // Create url for the request.
        String requestUrl = this.buildUrl();
        String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString();
        switch (httpMethod.toLowerCase(Locale.getDefault())) {
        case "get":
        case "delete":
        case "options":
        case "head":
        case "trace":
            HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString());
                }
            }

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long start = System.currentTimeMillis();

            // Executing the request.
            HttpResponse response = client.execute(httpRequest, localContext);
            long elapsed = System.currentTimeMillis() - start;

            return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl,
                    elapsed);
        default:
            HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase(
                    httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpEntityRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getEntityHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpEntityRequest.setHeader(header.get("key").getAsString(),
                            header.get("value").getAsString());
                }
            }

            // Setting the body of the request.
            StringEntity postEntity = new StringEntity(
                    this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString());
            httpEntityRequest.setEntity(postEntity);

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long entityRequestStart = System.currentTimeMillis();

            // Executing the request.
            HttpResponse entityResponse = client.execute(httpEntityRequest, localContext);
            long entityRequestDuration = System.currentTimeMillis() - entityRequestStart;
            return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl,
                    entityRequestDuration);
        }
    } catch (IOException e) {
        throw new TryItException(e.getMessage());
    }
}

From source file:org.ballerinalang.composer.service.workspace.tryit.HttpTryItClient.java

/**
 * {@inheritDoc}//from   w  w w. java2 s.c om
 */
@Override
public String execute() throws TryItException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpCoreContext localContext = new HttpCoreContext();
        // Create url for the request.
        String requestUrl = this.buildUrl();
        String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString();
        switch (httpMethod.toLowerCase(Locale.getDefault())) {
        case "get":
        case "delete":
        case "options":
        case "head":
        case "trace":
            HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString());
                }
            }

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long start = System.currentTimeMillis();

            // Executing the request.
            HttpResponse response = client.execute(httpRequest, localContext);
            long elapsed = System.currentTimeMillis() - start;

            return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl,
                    elapsed);
        default:
            HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase(
                    httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpEntityRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getEntityHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpEntityRequest.setHeader(header.get("key").getAsString(),
                            header.get("value").getAsString());
                }
            }

            // Setting the body of the request.
            StringEntity postEntity = new StringEntity(
                    this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString());
            httpEntityRequest.setEntity(postEntity);

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long entityRequestStart = System.currentTimeMillis();

            // Executing the request.
            HttpResponse entityResponse = client.execute(httpEntityRequest, localContext);
            long entityRequestDuration = System.currentTimeMillis() - entityRequestStart;
            return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl,
                    entityRequestDuration);
        }
    } catch (java.io.IOException e) {
        throw new TryItException(e.getMessage());
    }
}

From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java

/**
 * {@inheritDoc}/*from  ww  w . ja v  a  2 s .  c  om*/
 * @see org.opencastproject.loadtest.engage.util.remotetest.util.security.api.TrustedHttpClient#execute(org.apache.http.client.methods.HttpUriRequest)
 */
public HttpResponse execute(HttpUriRequest httpUriRequest) {
    // Add the request header to elicit a digest auth response
    httpUriRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);

    if ("GET".equalsIgnoreCase(httpUriRequest.getMethod())
            || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Run the request (the http client handles the multiple back-and-forth requests)
        try {
            return httpClient.execute(httpUriRequest);
        } catch (IOException e) {
            throw new TrustedHttpClientException(e);
        }
    }

    // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart
    // request), so we need to handle the details of the digest auth back-and-forth manually
    HttpRequestBase digestRequest;
    try {
        digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName());
    }
    digestRequest.setURI(httpUriRequest.getURI());
    digestRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    String[] realmAndNonce = getRealmAndNonce(digestRequest);

    if (realmAndNonce != null) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);

        // Set up the digest authentication with the required values
        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("realm", realmAndNonce[0]);
        digestAuth.overrideParamter("nonce", realmAndNonce[1]);

        // Add the authentication header
        try {
            httpUriRequest.addHeader(digestAuth.authenticate(creds, httpUriRequest));
        } catch (Exception e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }
    try {
        return httpClient.execute(httpUriRequest);
    } catch (Exception e) {
        // close the http connection(s)
        httpClient.getConnectionManager().shutdown();
        throw new TrustedHttpClientException(e);
    }
}

From source file:com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade.java

private void appendAccessTokenToQuery(HttpRequestBase request, OAuthBearerClientRequest oAuthClientRequest)
        throws OAuthSystemException {
    String queryString = getQueryStringFromOAuthClientRequest(oAuthClientRequest);
    URI oldUri = request.getURI();
    String requestQueryString = oldUri.getQuery() != null ? oldUri.getQuery() + "&" + queryString : queryString;

    try {/*from  ww w  . ja v  a2  s .c  o m*/
        request.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                oldUri.getRawPath(), requestQueryString, oldUri.getFragment()));
    } catch (URISyntaxException e) {
        throw new OAuthSystemException(e);
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.EndpointRequestFilter.java

@Override
public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String strURL = request.getEndpoint();
    strURL = PropertyExpander.expandProperties(context, strURL);
    try {/*from  w  ww .  java 2 s  . c o m*/
        if (StringUtils.hasContent(strURL)) {
            URI uri = new URI(strURL, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            httpMethod.setURI(new java.net.URI(uri.getScheme(), uri.getUserinfo(), uri.getHost(), uri.getPort(),
                    (uri.getPath()) == null ? "/" : uri.getPath(), uri.getQuery(), uri.getFragment()));
        }
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:com.wudaosoft.net.httpclient.ParameterRequestBuilder.java

public static HttpUriRequest build(RequestBuilder builder) {

    final HttpRequestBase result;
    URI uriNotNull = builder.getUri() != null ? builder.getUri() : URI.create("/");
    Charset charset = builder.getCharset();
    charset = charset != null ? charset : HTTP.DEF_CONTENT_CHARSET;
    String method = builder.getMethod();
    List<NameValuePair> parameters = builder.getParameters();
    HttpEntity entityCopy = builder.getEntity();

    if (parameters != null && !parameters.isEmpty()) {
        if (entityCopy == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method)
                || HttpPut.METHOD_NAME.equalsIgnoreCase(method)
                || HttpPatch.METHOD_NAME.equalsIgnoreCase(method))) {
            entityCopy = new UrlEncodedFormEntity(parameters, charset);
        } else {/* w  w w.  jav a  2  s .  com*/
            try {
                uriNotNull = new URIBuilder(uriNotNull).setCharset(charset).addParameters(parameters).build();
            } catch (final URISyntaxException ex) {
                // should never happen
            }
        }
    }

    if (entityCopy == null) {
        result = new InternalRequest(method);
    } else {
        final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method);
        request.setEntity(entityCopy);
        result = request;
    }
    result.setProtocolVersion(builder.getVersion());
    result.setURI(uriNotNull);
    // if (builder.headergroup != null) {
    // result.setHeaders(builder.headergroup.getAllHeaders());
    // }
    result.setConfig(builder.getConfig());
    return result;
}

From source file:com.sap.core.odata.fit.ref.AbstractRefTest.java

protected HttpResponse callUri(final ODataHttpMethod httpMethod, final String uri,
        final String additionalHeader, final String additionalHeaderValue, final String requestBody,
        final String requestContentType, final HttpStatusCodes expectedStatusCode) throws Exception {

    HttpRequestBase request = httpMethod == ODataHttpMethod.GET ? new HttpGet()
            : httpMethod == ODataHttpMethod.DELETE ? new HttpDelete()
                    : httpMethod == ODataHttpMethod.POST ? new HttpPost()
                            : httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
    request.setURI(URI.create(getEndpoint() + uri));
    if (additionalHeader != null) {
        request.addHeader(additionalHeader, additionalHeaderValue);
    }//from   ww  w .  j a  v  a 2s.  c  om
    if (requestBody != null) {
        ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
        request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
    }

    final HttpResponse response = getHttpClient().execute(request);

    assertNotNull(response);
    assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

    if (expectedStatusCode == HttpStatusCodes.OK) {
        assertNotNull(response.getEntity());
        assertNotNull(response.getEntity().getContent());
    } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
        assertNotNull(response.getEntity());
        assertNotNull(response.getEntity().getContent());
        assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
    } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
        assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
    }

    return response;
}

From source file:de.cosmocode.issuetracker.activecollab.DefaultActiveCollab.java

private JsonNode request(HttpRequestBase request, String pathInfo) throws IOException {
    final URI requestUri;
    try {/*from www  .  ja  va 2s.c  o  m*/
        requestUri = new URI(apiUri.toString() + "?token=" + token + "&path_info=" + pathInfo);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    request.setURI(requestUri);

    request.setHeader("Accept", "application/json");

    final ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(request, responseHandler);

    return mapper.readValue(response, JsonNode.class);
}