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.instagram4j.DefaultInstagramClient.java

@SuppressWarnings("unchecked")
private <T> Result<T[]> requestEntities(HttpRequestBase method, Class<T> type) throws InstagramException {
    method.getParams().setParameter("http.useragent", "Instagram4j/1.0");

    JsonParser jp = null;//  w  w  w .  j av  a  2  s  . com
    HttpResponse response = null;
    ResultMeta meta = null;

    try {
        method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        setEnforceHeader(method);

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000);
        client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);

        if (LOG.isDebugEnabled())
            LOG.debug(String.format("Requesting entities entry point %s, method %s", method.getURI().toString(),
                    method.getMethod()));

        autoThrottle();

        response = client.execute(method);

        jp = createParser(response, method);

        JsonToken tok = jp.nextToken();
        if (tok != JsonToken.START_OBJECT) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                        null, null);

            throw createInstagramException("Invalid response format from Instagram API",
                    method.getURI().toString(), response, null, null);
        }

        Pagination pagination = null;
        T[] data = null;

        while (true) {
            tok = jp.nextValue();
            if (tok == JsonToken.START_ARRAY) {
                // Should be "data"
                String name = jp.getCurrentName();
                if (!"data".equals(name))
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);

                List<T> items = new ArrayList<T>();

                tok = jp.nextToken();
                if (tok == JsonToken.START_OBJECT) {
                    if (type != null) {
                        T item;
                        while ((item = jp.readValueAs(type)) != null)
                            items.add(item);
                    } else
                        jp.readValueAs(Map.class); // Consume & ignore
                }

                data = (T[]) Array.newInstance(type, items.size());
                System.arraycopy(items.toArray(), 0, data, 0, items.size());
            } else if (tok == JsonToken.START_OBJECT) {
                // Should be "pagination" or "meta"
                String name = jp.getCurrentName();
                if ("pagination".equals(name))
                    pagination = jp.readValueAs(Pagination.class);
                else if ("meta".equals(name))
                    meta = jp.readValueAs(ResultMeta.class);
                else
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);
            } else
                break;
        }

        if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                    null, null);

        Result<T[]> result = new Result<T[]>(pagination, meta, data);
        setRateLimits(response, result);

        return result;
    } catch (JsonParseException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (JsonProcessingException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (IOException e) {
        throw createInstagramException("Error communicating with Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } finally {
        if (jp != null)
            try {
                jp.close();
            } catch (IOException e) {
            }
        method.releaseConnection();
    }
}

From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java

public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request,
        Credentials credentials) throws HttpRequestException {

    LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request);

    CloseableHttpResponse response;/*  w w  w  . java  2 s.c  om*/

    request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0"));
    request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8"));

    HttpAuthorization.authorize(request, credentials);

    // use defaults: 3 retries, 2 second wait between attempts
    RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy();

    while (retryStrategy.shouldRetry()) {

        try {

            response = httpClient.execute(request);

            StatusLine statusLine = response.getStatusLine();
            HttpEntity responseEntity = response.getEntity();

            if (statusLine.getStatusCode() >= 300) {
                String responseText = statusLine.getReasonPhrase();
                if (responseEntity != null) {
                    responseText = parseError(EntityUtils.toString(responseEntity));
                    LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText);
                }
                throw new HttpResponseException(statusLine.getStatusCode(), responseText);
            }
            if (responseEntity == null) {
                throw new ClientProtocolException("Response contains no content");
            }

            return response; // don't close response yet, it is not consumed!
        }

        // if we didn't get a response at all, try again
        catch (NoHttpResponseException nhre) {
            LOGGER.warn("Thread: {}, No response from server:  Retrying in {} milliseconds, retries left: {}",
                    Thread.currentThread().getId(), retryStrategy.getTimeToWait(),
                    retryStrategy.numberOfTriesLeft);
            retryStrategy.errorOccurred();
        } catch (RetryException re) {
            throw new HttpRequestException(request, re);
        } catch (ClientProtocolException uhe) {
            throw new ConnectionException(request.getURI().toString(), uhe);
        } catch (IOException ioe) {
            throw new HttpRequestException(request, ioe);
        }

        // here we catch any exception we throw above (plus any we didn't throw ourselves),
        // log the problem, close any connection held by the request
        // and then rethrow the exception to the caller.
        catch (Exception exception) {
            LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(),
                    exception.getCause().getLocalizedMessage());
            request.releaseConnection();
            throw exception;
        }
    }
    throw new RuntimeException("Fatal Exception: Should not have occurred!");
}

From source file:com.pennassurancesoftware.tutum.client.TutumClient.java

private String evaluateResponse(HttpRequestBase request, HttpResponse httpResponse) throws TutumException {
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String response = "";

    if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_CREATED == statusCode
            || HttpStatus.SC_ACCEPTED == statusCode) {
        response = httpResponseToString(httpResponse);
        if (LOG.isDebugEnabled()) {
            String jsonStr = response;
            jsonStr = jsonStr == null || "".equals(jsonStr) ? "{}" : jsonStr;
            LOG.debug("Target URL: {}", request.getURI());
            LOG.debug("JSON Message: {}", StringUtils.defaultIfEmpty(getRequestMessage(request), "N/A"));
            LOG.debug("JSON Response: {}", jsonStr);
        }/*  ww  w  .ja va 2 s .c  o  m*/
    } else if (HttpStatus.SC_NO_CONTENT == statusCode) {
        // in a way its always true from client perspective if there is no exception.
        response = String.format(Constants.NO_CONTENT_JSON_STRUCT, statusCode);
    }

    if ((statusCode >= 400 && statusCode < 510)) {
        String jsonStr = httpResponseToString(httpResponse);
        jsonStr = jsonStr == null || "".equals(jsonStr) ? "{}" : jsonStr;
        LOG.error("Target URL: {}", request.getURI());
        LOG.error("JSON Message: {}", getRequestMessage(request));
        LOG.error("JSON Response: {}", jsonStr);

        final JsonObject jsonObj = jsonParser.parse(jsonStr).getAsJsonObject();
        final String message = jsonObj.has("error") ? jsonObj.get("error").getAsString() : jsonStr;
        String errorMsg = String.format("\nHTTP Status Code: %s\nError Message: %s", statusCode, message);
        LOG.debug(errorMsg);

        throw new TutumException(errorMsg, "N/A", statusCode);
    }

    return response;
}

From source file:org.instagram4j.DefaultInstagramClient.java

private <T> Result<T> requestEntity(HttpRequestBase method, Class<T> type, boolean signableRequest)
        throws InstagramException {
    method.getParams().setParameter("http.useragent", "Instagram4j/1.0");

    JsonParser jp = null;/*  ww w. j av  a2  s. c  om*/
    HttpResponse response = null;
    ResultMeta meta = null;

    try {
        method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        if (signableRequest)
            setEnforceHeader(method);

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000);
        client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);

        if (LOG.isDebugEnabled())
            LOG.debug(String.format("Requesting entity entry point %s, method %s", method.getURI().toString(),
                    method.getMethod()));

        autoThrottle();

        response = client.execute(method);

        jp = createParser(response, method);

        JsonToken tok = jp.nextToken();
        if (tok != JsonToken.START_OBJECT) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                        null, null);

            throw createInstagramException("Invalid response format from Instagram API",
                    method.getURI().toString(), response, null, null);
        }

        T data = null;

        while (true) {
            tok = jp.nextValue();
            if (tok == JsonToken.START_ARRAY) {
                throw createInstagramException("Unexpected array in entity response " + jp.getCurrentName(),
                        method.getURI().toString(), response, meta, null);
            } else if (tok == JsonToken.START_OBJECT) {
                // Should be "data" or "meta"
                String name = jp.getCurrentName();
                if ("meta".equals(name))
                    meta = jp.readValueAs(ResultMeta.class);
                else if ("data".equals(name)) {
                    if (type != null)
                        data = jp.readValueAs(type);
                    else
                        jp.readValueAs(Map.class); // Consume & ignore
                } else
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);
            } else
                break;
        }

        if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                    null, null);

        Result<T> result = new Result<T>(null, meta, data);
        setRateLimits(response, result);

        return result;
    } catch (JsonParseException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (JsonProcessingException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (IOException e) {
        throw createInstagramException("Error communicating with Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } finally {
        if (jp != null)
            try {
                jp.close();
            } catch (IOException e) {
            }
        method.releaseConnection();
    }
}

From source file:groovyx.net.http.HTTPBuilder.java

/**
 * All <code>request</code> methods delegate to this method.
 *//*  w  w w .j  ava  2  s  .c o m*/
protected Object doRequest(final RequestConfigDelegate delegate) throws ClientProtocolException, IOException {

    final HttpRequestBase reqMethod = delegate.getRequest();

    Object contentType = delegate.getContentType();

    if (this.autoAcceptHeader) {
        String acceptContentTypes = contentType.toString();
        if (contentType instanceof ContentType)
            acceptContentTypes = ((ContentType) contentType).getAcceptHeader();
        reqMethod.setHeader("Accept", acceptContentTypes);
    }

    reqMethod.setURI(delegate.getUri().toURI());
    if (reqMethod.getURI() == null)
        throw new IllegalStateException("Request URI cannot be null");

    log.debug(reqMethod.getMethod() + " " + reqMethod.getURI());

    // set any request headers from the delegate
    Map<?, ?> headers = delegate.getHeaders();
    for (Object key : headers.keySet()) {
        Object val = headers.get(key);
        if (key == null)
            continue;
        if (val == null)
            reqMethod.removeHeaders(key.toString());
        else
            reqMethod.setHeader(key.toString(), val.toString());
    }

    HttpResponseDecorator resp = new HttpResponseDecorator(client.execute(reqMethod, delegate.getContext()),
            delegate.getContext(), null);
    try {
        int status = resp.getStatusLine().getStatusCode();
        Closure responseClosure = delegate.findResponseHandler(status);
        log.debug("Response code: " + status + "; found handler: " + responseClosure);

        Object[] closureArgs = null;
        switch (responseClosure.getMaximumNumberOfParameters()) {
        case 1:
            closureArgs = new Object[] { resp };
            break;
        case 2: // parse the response entity if the response handler expects it:
            HttpEntity entity = resp.getEntity();
            try {
                if (entity == null || entity.getContentLength() == 0)
                    closureArgs = new Object[] { resp, null };
                else
                    closureArgs = new Object[] { resp, parseResponse(resp, contentType) };
            } catch (Exception ex) {
                Header h = entity.getContentType();
                String respContentType = h != null ? h.getValue() : null;
                log.warn("Error parsing '" + respContentType + "' response", ex);
                throw new ResponseParseException(resp, ex);
            }
            break;
        default:
            throw new IllegalArgumentException("Response closure must accept one or two parameters");
        }

        Object returnVal = responseClosure.call(closureArgs);
        log.trace("response handler result: " + returnVal);

        return returnVal;
    } finally {
        HttpEntity entity = resp.getEntity();
        if (entity != null)
            entity.consumeContent();
    }
}

From source file:net.oauth.client.httpclient4.HttpClient4.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpRequestBase httpRequest;
    if (isPost || isPut) {
        HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            excerpt = e.getExcerpt();/*from  w ww.  ja  v a  2  s. c  om*/
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod
                    .setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length)));
        }
        httpRequest = entityEnclosingMethod;
    } else if (isDelete) {
        httpRequest = new HttpDelete(url);
    } else {
        httpRequest = new HttpGet(url);
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpRequest.addHeader(header.getKey(), header.getValue());
    }
    HttpParams params = httpRequest.getParams();
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(value));
        } else if (CONNECT_TIMEOUT.equals(name)) {
            params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.parseInt(value));
        }
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString()));
    HttpResponse httpResponse = client.execute(httpRequest);
    return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset());
}

From source file:com.ibm.sbt.services.client.ClientService.java

/**
 * Find the handler for the specified response
 * //from  ww w .j  ava 2  s  .  c o  m
 * @param request
 * @param response
 * @param DateFormat
 * @return
 * @throws ClientServicesException
 */
protected Handler findHandler(HttpRequestBase request, HttpResponse response, Handler handler)
        throws ClientServicesException {
    if (logger.isLoggable(Level.FINEST)) {
        logger.entering(sourceClass, "findHandler",
                new Object[] { request.getURI(), response.getStatusLine(), handler });
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            handler = findErrorHandler(request, response);
        }

        // Connections Delete API returns SC_NO_CONTENT for successful deletion.
        if (isErrorStatusCode(statusCode)) {
            handler = findErrorHandler(request, response);
        }

        if (handler == null) {
            handler = findSuccessHandler(request, response);
        }

        // SBT doesn't have a JS interpreter...
        if (handler == null) {
            handler = new HandlerRaw();
        }
    } catch (Exception ex) {
        if (ex instanceof ClientServicesException) {
            throw (ClientServicesException) ex;
        }
        throw new ClientServicesException(ex, "Error while parsing the REST service results");
    }

    if (logger.isLoggable(Level.FINEST)) {
        logger.exiting(sourceClass, "findHandler", handler);
    }
    return handler;
}

From source file:com.ibm.sbt.services.client.ClientService.java

/**
 * Process the specified response/*from   w  w w  .  j a  va2  s .c  o m*/
 * 
 * @param httpClient
 * @param httpRequestBase
 * @param httpResponse
 * @param args
 * @return
 * @throws ClientServicesException
 */
protected Response processResponse(HttpClient httpClient, HttpRequestBase httpRequestBase,
        HttpResponse httpResponse, Args args) throws ClientServicesException {
    if (logger.isLoggable(Level.FINEST)) {
        logger.entering(sourceClass, "processResponse",
                new Object[] { httpRequestBase.getURI(), httpResponse.getStatusLine() });
    }

    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    if (!checkStatus(statusCode)) {
        if (SbtCoreLogger.SBT.isErrorEnabled()) {
            // Do not throw an exception here as some of the non OK responses are not error cases.
            String msg = "Client service request to: {0} did not return OK status. Status returned: {1}, reason: {2}, expected: {3}";
            msg = StringUtil.format(msg, httpRequestBase.getURI(), statusCode, reasonPhrase, HttpStatus.SC_OK);
            SbtCoreLogger.SBT.traceDebugp(this, "processResponse", msg);
        }
    }

    if (isResponseRequireAuthentication(httpResponse)) {
        forceAuthentication(args);
        throw new ClientServicesException(new AuthenticationException());
    }

    Handler format = findHandler(httpRequestBase, httpResponse, args.handler);

    Response response = new Response(httpClient, httpResponse, httpRequestBase, args, format);

    if (logger.isLoggable(Level.FINEST)) {
        logger.exiting(sourceClass, "processResponse", response);
    }
    return response;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public HootResult synchronousExecute(HootRequest request) {

    HttpRequestBase requestBase = null;
    HootResult result = request.getResult();
    try {/*  ww w.jav  a  2s  .  c o  m*/
        String uri = request.buildUri().toString();
        switch (request.getOperation()) {
        case DELETE:
            requestBase = new HttpDelete(uri);
            break;
        case GET:
            requestBase = new HttpGet(uri);
            break;
        case PUT:
            HttpPut put = new HttpPut(uri);
            put.setEntity(getEntity(request));
            requestBase = put;
            break;
        case POST:
            HttpPost post = new HttpPost(uri);
            post.setEntity(getEntity(request));
            requestBase = post;
            break;
        case HEAD:
            requestBase = new HttpHead(uri);
            break;
        }
    } catch (UnsupportedEncodingException e1) {
        result.setException(e1);
        e1.printStackTrace();
        return result;
    } catch (IOException e) {
        result.setException(e);
        e.printStackTrace();
        return result;
    }

    synchronized (mRequestBaseMap) {
        mRequestBaseMap.put(request, requestBase);
    }
    if (request.getHeaders() != null && request.getHeaders().size() > 0) {
        for (Object propertyKey : request.getHeaders().keySet()) {
            requestBase.addHeader((String) propertyKey, (String) request.getHeaders().get(propertyKey));
        }
    }

    InputStream is = null;
    try {
        Log.v(TAG, "URI: [" + requestBase.getURI().toString() + "]");
        HttpResponse response = mClient.execute(requestBase);

        if (response != null) {
            result.setResponseCode(response.getStatusLine().getStatusCode());
            Map<String, List<String>> headers = new HashMap<String, List<String>>();
            for (Header header : response.getAllHeaders()) {
                List<String> values = new ArrayList<String>();
                values.add(header.getValue());
                headers.put(header.getName(), values);
            }
            result.setHeaders(headers);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                result.setResponseStream(new BufferedInputStream(is));
                request.deserializeResult();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        result.setException(e);
    } finally {
        requestBase = null;
        synchronized (mRequestBaseMap) {
            mRequestBaseMap.remove(request);
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}