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

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

Introduction

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

Prototype

public URI getURI() 

Source Link

Document

Returns the original request URI.

Usage

From source file:org.cloudifysource.restclient.GSRestClient.java

/**
 * This method executes the given Http request and analyzes the response. Successful responses are expected to be
 * formatted as json strings, and are converted to a Map<String, Object> object. In this map these keys can be
 * expected: "status" (success/error), "error"(reason code), "error_args" and "response".
 * <p/>/*w ww  .  ja v  a2s .  c om*/
 * Errors of all types (IO, Http, rest etc.) are reported through an ErrorStatusException.
 *
 * @param httpMethod
 *            The http request to perform.
 * @param responseJsonKey
 *            specify a key for a response attribute to be returned, null means return the entire response
 * @return An object, the response body received from the rest service
 * @throws ErrorStatusException
 *             Reporting errors of all types (IO, HTTP, rest etc.)
 */

private Object executeHttpMethod(final HttpRequestBase httpMethod, final String responseJsonKey)
        throws ErrorStatusException {
    String responseBody;
    try {
        final HttpResponse response = httpClient.execute(httpMethod);

        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != CloudifyConstants.HTTP_STATUS_CODE_OK) {
            final String reasonPhrase = response.getStatusLine().getReasonPhrase();
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, httpMethod.getURI() + MSG_RESPONSE_CODE + statusCode + ", "
                        + MSG_RESPONSE_REASON_PHRASE + ": " + reasonPhrase);
            }
            responseBody = getResponseBody(response, httpMethod);
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, httpMethod.getURI() + " response body " + responseBody);
            }

            if (statusCode == CloudifyConstants.HTTP_STATUS_NOT_FOUND) {
                throw new ErrorStatusException("URL_not_found", httpMethod.getURI());
            } else if (statusCode == CloudifyConstants.HTTP_STATUS_ACCESS_DENIED) {
                throw new ErrorStatusException(CloudifyErrorMessages.NO_PERMISSION_ACCESS_DENIED.getName(),
                        httpMethod.getURI());
            } else if (statusCode == CloudifyConstants.HTTP_STATUS_UNAUTHORIZED) {
                throw new ErrorStatusException(CloudifyErrorMessages.UNAUTHORIZED.getName(), reasonPhrase,
                        httpMethod.getURI());
            }

            final Map<String, Object> errorMap = GSRestClient.jsonToMap(responseBody);
            final String status = (String) errorMap.get(STATUS_KEY);
            if (ERROR.equals(status)) {
                final String reason = (String) errorMap.get(ERROR);
                @SuppressWarnings("unchecked")
                final List<Object> reasonsArgs = (List<Object>) errorMap.get(ERROR_ARGS);
                final ErrorStatusException e = new ErrorStatusException(reason,
                        reasonsArgs != null ? reasonsArgs.toArray() : null);
                if (errorMap.containsKey(VERBOSE)) {
                    e.setVerboseData((String) errorMap.get(VERBOSE));
                }
                logger.log(Level.FINE, reason, e);
                throw e;
            }

        }

        responseBody = getResponseBody(response, httpMethod);
        final Map<String, Object> responseMap = GSRestClient.jsonToMap(responseBody);
        return responseJsonKey != null ? responseMap.get(RESPONSE_KEY) : responseMap;
    } catch (final IOException e) {
        logger.log(Level.INFO, httpMethod.getURI() + MSG_REST_API_ERR, e);
        throw new ErrorStatusException(e, REASON_CODE_COMM_ERR, httpMethod.getURI(), e.getMessage());
    } finally {
        httpMethod.abort();
    }
}

From source file:com.evolveum.polygon.connector.drupal.DrupalConnector.java

protected JSONArray callRequest(HttpRequestBase request) throws IOException {
    LOG.ok("request URI: {0}", request.getURI());
    request.setHeader("Content-Type", CONTENT_TYPE);

    authHeader(request);//from  w w  w  .  ja  v a 2  s .  co m

    CloseableHttpResponse response = execute(request);
    LOG.ok("response: {0}", response);
    processDrupalResponseErrors(response);

    String result = EntityUtils.toString(response.getEntity());
    LOG.ok("response body: {0}", result);
    closeResponse(response);
    return new JSONArray(result);
}

From source file:com.evolveum.polygon.connector.drupal.DrupalConnector.java

protected JSONObject callRequest(HttpRequestBase request, boolean parseResult) throws IOException {
    LOG.ok("request URI: {0}", request.getURI());
    request.setHeader("Content-Type", CONTENT_TYPE);

    authHeader(request);// ww w .  j ava  2s .co  m

    CloseableHttpResponse response = null;
    response = execute(request);
    LOG.ok("response: {0}", response);
    processDrupalResponseErrors(response);

    if (!parseResult) {
        closeResponse(response);
        return null;
    }
    String result = EntityUtils.toString(response.getEntity());
    LOG.ok("response body: {0}", result);
    closeResponse(response);
    return new JSONObject(result);
}

From source file:com.guster.brandon.library.webservice.RequestHandler.java

/**
 * Main method of sending HTTP Request to the server
 * @param rq Apache HTTP Base Request/*from  w  w  w  .  j a va 2s  .c  o m*/
 * @return Response, if no response from the server or no internet connection,
 *          this object will return null
 * @throws IOException
 */
private Response send(HttpRequestBase rq) throws IOException {
    //Log.d("NISSAN", "WebService: Connecting to url... " + rq.getURI());
    HttpResponse httpResponse = httpClient.execute(rq);
    HttpEntity entity = httpResponse.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream inputStream = bufHttpEntity.getContent();
    InputStream rawInputStream = bufHttpEntity.getContent();

    // variables to be put into Response
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
    long contentLength = entity.getContentLength();

    // onPrepare the response
    Response responseObject = new Response();
    responseObject.setStatusCode(statusCode);
    responseObject.setStatusDesc(statusDesc);
    responseObject.setContentLength(contentLength);
    responseObject.setRawResponse(rawInputStream);
    responseObject.setContentEncoding(entity.getContentEncoding());
    responseObject.setContentType(entity.getContentType());
    responseObject.setUrl(rq.getURI().toString());

    return responseObject;
}

From source file:net.elasticgrid.rackspace.common.RackspaceConnection.java

/**
 * Make a http request and process the response. This method also performs automatic retries.
 *
 * @param request  the HTTP method to use (GET, POST, DELETE, etc)
 * @param respType the class that represents the desired/expected return type
 * @return the unmarshalled entity//from  w  ww  .j ava2  s.c o m
 * @throws RackspaceException
 * @throws IOException        if there is an I/O exception
 * @throws HttpException      if there is an HTTP exception
 * @throws JiBXException      if the result can't be unmarshalled
 */
@SuppressWarnings("unchecked")
protected <T> T makeRequest(HttpRequestBase request, Class<T> respType)
        throws HttpException, IOException, JiBXException, RackspaceException {

    if (!authenticated)
        authenticate();

    // add auth params, and protocol specific headers
    request.addHeader("X-Auth-Token", getAuthToken());

    // set accept and content-type headers
    request.setHeader("Accept", "application/xml; charset=UTF-8");
    request.setHeader("Accept-Encoding", "gzip");
    request.setHeader("Content-Type", "application/xml; charset=UTF-8");

    // send the request
    T result = null;
    boolean done = false;
    int retries = 0;
    boolean doRetry = false;
    RackspaceException error = null;
    do {
        HttpResponse response = null;
        if (retries > 0)
            logger.log(Level.INFO, "Retry #{0}: querying via {1} {2}",
                    new Object[] { retries, request.getMethod(), request.getURI() });
        else
            logger.log(Level.INFO, "Querying via {0} {1}",
                    new Object[] { request.getMethod(), request.getURI() });

        if (logger.isLoggable(Level.FINEST) && request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity();
            if (entity instanceof EntityTemplate) {
                EntityTemplate template = (EntityTemplate) entity;
                ByteArrayOutputStream baos = null;
                try {
                    baos = new ByteArrayOutputStream();
                    template.writeTo(baos);
                    logger.log(Level.FINEST, "Request body:\n{0}", baos.toString());
                } finally {
                    IOUtils.closeQuietly(baos);
                }
            }
        }

        InputStream entityStream = null;
        HttpEntity entity = null;

        if (logger.isLoggable(Level.FINEST)) {
            response = getHttpClient().execute(request);
            entity = response.getEntity();
            try {
                entityStream = entity.getContent();
                logger.log(Level.FINEST, "Response body on " + request.getURI() + " via " + request.getMethod()
                        + ":\n" + IOUtils.toString(entityStream));
            } finally {
                IOUtils.closeQuietly(entityStream);
            }
        }

        response = getHttpClient().execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        entity = response.getEntity();

        switch (statusCode) {
        case 200:
        case 202:
        case 203:
            try {
                entityStream = entity.getContent();
                IBindingFactory bindingFactory = BindingDirectory.getFactory(respType);
                IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext();
                result = (T) unmarshallingCxt.unmarshalDocument(entityStream, "UTF-8");
            } finally {
                entity.consumeContent();
                IOUtils.closeQuietly(entityStream);
            }
            done = true;
            break;
        case 503: // service unavailable
            logger.log(Level.WARNING, "Service unavailable on {0} via {1}. Will retry in {2} seconds.",
                    new Object[] { request.getURI(), request.getMethod(), Math.pow(2.0, retries + 1) });
            doRetry = true;
            break;
        case 401: // unauthorized
            logger.warning("Not authenticated or authentication token expired. Authenticating...");
            authenticate();
            doRetry = true;
            break;
        case 417:
            throw new RackspaceException(new IllegalArgumentException("Some parameters are invalid!")); // TODO: temp hack 'til Rackspace API is fixed!
        case 400:
        case 500:
        default:
            try {
                entityStream = entity.getContent();
                IBindingFactory bindingFactory = BindingDirectory.getFactory(CloudServersAPIFault.class);
                IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext();
                CloudServersAPIFault fault = (CloudServersAPIFault) unmarshallingCxt
                        .unmarshalDocument(entityStream, "UTF-8");
                done = true;
                throw new RackspaceException(fault.getCode(), fault.getMessage(), fault.getDetails());
            } catch (JiBXException e) {
                response = getHttpClient().execute(request);
                entity = response.getEntity();
                entityStream = entity.getContent();
                logger.log(Level.SEVERE, "Can't unmarshal response from " + request.getURI() + " via "
                        + request.getMethod() + ":" + IOUtils.toString(entityStream));
                e.printStackTrace();
                throw e;
            } finally {
                entity.consumeContent();
                IOUtils.closeQuietly(entityStream);
            }
        }

        if (doRetry) {
            retries++;
            if (retries > maxRetries) {
                throw new HttpException("Number of retries exceeded for " + request.getURI(), error);
            }
            doRetry = false;
            try {
                Thread.sleep((int) Math.pow(2.0, retries) * 1000);
            } catch (InterruptedException ex) {
                // do nothing
            }
        }
    } while (!done);

    return result;
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java

protected void execute(HttpRequestBase httpBaseRequest, CredentialItem credentialItem, List<CookieItem> cookies)
        throws ClientProtocolException, IOException, URISyntaxException {

    if (!CollectionUtils.isEmpty(cookies)) {
        List<Cookie> cookieList = cookieStore.getCookies();
        for (CookieItem cookie : cookies) {
            Cookie newCookie = cookie.getCookie();
            if (!cookieList.contains(newCookie))
                cookieStore.addCookie(newCookie);
        }/* w ww  .j a v a 2s. c  om*/
    }

    this.httpBaseRequest = httpBaseRequest;

    // No more than one 1 minute to establish the connection
    // No more than 10 minutes to establish the socket
    // Enable stales connection checking
    // Cookies uses browser compatibility
    RequestConfig.Builder configBuilber = RequestConfig.custom().setSocketTimeout(1000 * 60 * 10)
            .setConnectTimeout(1000 * 60).setStaleConnectionCheckEnabled(true)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);

    if (credentialItem == null)
        credentialsProvider.clear();
    else
        credentialItem.setUpCredentials(credentialsProvider);

    URI uri = httpBaseRequest.getURI();
    if (proxyHandler != null)
        proxyHandler.check(configBuilber, uri, credentialsProvider);

    httpBaseRequest.setConfig(configBuilber.build());

    httpClientContext = new HttpClientContext();

    httpResponse = httpClient.execute(httpBaseRequest, httpClientContext);
    if (httpResponse == null)
        return;
    statusLine = httpResponse.getStatusLine();
    httpEntity = httpResponse.getEntity();
}

From source file:de.betterform.connector.http.RedirectingHTTPSubmissionHandler.java

/**
 * Override the execute method to redirect if appropriate
 *///from  w ww .j a va  2 s  . c  o m
protected void execute(HttpRequestBase httpMethod) throws Exception {
    LOGGER.info("RedirectingHTTPSubmissionDriver.execute");
    HttpParams httpParams = new BasicHttpParams();
    HttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams);

    HttpResponse response = client.execute(httpMethod);

    if (response.getStatusLine().getStatusCode() >= 400) {
        throw new XFormsException("HTTP status " + response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase());
    }

    String locationURL = null;

    // if Created then redirect to the new uri
    if (response.getStatusLine().getStatusCode() == 201) {
        Header locationURLHdr = response.getFirstHeader("Location");
        if (null == locationURLHdr)
            locationURLHdr = response.getFirstHeader("location");
        if (null == locationURLHdr)
            locationURLHdr = response.getFirstHeader("Content-Location");
        if (null == locationURLHdr)
            locationURLHdr = response.getFirstHeader("content-location");

        if (null != locationURLHdr) {
            locationURL = locationURLHdr.getValue();
        }

    }
    // if Updated with no content then redirect to the existing uri
    // (i.e. not the betterForm post address)
    else if (response.getStatusLine().getStatusCode() == 204) {
        locationURL = httpMethod.getURI().toString();
        // make sure redirects to the container
        // i.e. strip off any filename
        // (NOTE this is probably specific to my situation)
        // need access to the referer from the incoming http request)
        int idx = locationURL.lastIndexOf('/');
        if (idx > -1) {
            locationURL = locationURL.substring(0, idx + 1);
        }
    }

    if (null != locationURL) {
        LOGGER.info("Redirecting to location: " + locationURL);

        this.mySubmission.redirect(locationURL);
    }

    this.handleHttpMethod(response);
}

From source file:se.kodapan.io.http.HttpAccessor.java

public Response sendRequest(HttpRequestBase method, boolean followRedirects) throws IOException {

    // lazy opening
    if (!open) {/*  w w w  . j ava2  s. c o  m*/
        open();
    }

    // Mimics a Firefox on OS X.

    if (method.getHeaders("User-Agent").length == 0) {
        method.addHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; sv-SE; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2");
    }
    if (method.getHeaders("Accept").length == 0) {
        method.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    }
    if (method.getHeaders("Accept-Language").length == 0) {
        method.addHeader("Accept-Language", "sv-se,sv;q=0.8,en-us;q=0.5,en;q=0.3");
    }
    if (method.getHeaders("Accept-Charset").length == 0) {
        method.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    }

    Response response = new Response();
    URI url = method.getURI();
    response.finalURL = url;

    if (log.isDebugEnabled()) {
        log.debug("Requesting " + url);
    }

    String tmp = url.toString().toLowerCase();
    if (!(tmp.startsWith("http://") || tmp.startsWith("https://"))) {
        log.error("Unsupported protocol in url " + url);
        return response;
    }

    if (followRedirects) {
        try {
            response.success = downloadFollowRedirects(new Request(method), response);
        } catch (SAXException e) {
            log.error("Attempting to follow redirection chain", e);
            return response;
        }
    } else {
        response.success = download(new Request(method), response);
    }

    return response;

}