Example usage for org.apache.http.client.methods HttpUriRequest getMethod

List of usage examples for org.apache.http.client.methods HttpUriRequest getMethod

Introduction

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

Prototype

String getMethod();

Source Link

Document

Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other.

Usage

From source file:com.floragunn.searchguard.HeaderAwareJestHttpClient.java

public Tuple<JestResult, HttpResponse> executeE(final Action clientRequest) throws IOException {

    final String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI());

    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));

    log.debug("reqeust method and restUrl - " + clientRequest.getRestMethodName() + " " + elasticSearchRestUrl);

    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Iterator<Entry> it = clientRequest.getHeaders().entrySet().iterator(); it.hasNext();) {
            final Entry header = it.next();
            request.addHeader((String) header.getKey(), header.getValue().toString());
        }/*w  ww.  java  2  s. co m*/
    }

    final HttpResponse response = httpClient.execute(request);

    // If head method returns no content, it is added according to response code thanks to https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        if (response.getEntity() == null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
            }
        }
    }
    return new Tuple(deserializeResponse(response, clientRequest), response);
}

From source file:com.keydap.sparrow.SparrowClient.java

/**
 * Sends the given request to the server
 * /*from  w w  w  .jav a 2s.c  o  m*/
 * @param req the HTTP request
 * @param resClas class of the resourcetype
 * @return
 */
public <T> Response<T> sendRawRequest(HttpUriRequest req, Class<T> resClas) {
    Response<T> result = new Response<T>();
    try {
        authenticator.addHeaders(req);
        LOG.debug("Sending {} request to {}", req.getMethod(), req.getURI());
        HttpResponse resp = client.execute(req);
        authenticator.saveHeaders(resp);
        StatusLine sl = resp.getStatusLine();
        int code = sl.getStatusCode();

        LOG.debug("Received status code {} from the request to {}", code, req.getURI());
        HttpEntity entity = resp.getEntity();
        String json = null;
        if (entity != null) {
            json = EntityUtils.toString(entity);
        }

        result.setHttpCode(code);

        // if it is success there will be response body to read
        if (code == SC_OK || code == SC_CREATED || code == SC_NOT_MODIFIED) {
            if (json != null) { // some responses have no body, so check for null
                T t = unmarshal(json, resClas);
                result.setResource(t);
            }
        } else {
            if (json != null) {
                Error error = serializer.fromJson(json, Error.class);
                result.setError(error);
            }
        }

        result.setHttpBody(json);
        result.setHeaders(resp.getAllHeaders());
    } catch (Exception e) {
        LOG.warn("", e);
        result.setHttpCode(-1);
        Error err = new Error();

        err.setDetail(e.getMessage());
        result.setError(err);
    }

    return result;
}

From source file:com.petalmd.armor.HeaderAwareJestHttpClient.java

public Tuple<JestResult, HttpResponse> executeE(final Action clientRequest) throws IOException {

    final String elasticSearchRestUrl = getRequestURL(getNextServer(), clientRequest.getURI());

    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));

    log.debug("reqeust method and restUrl - " + clientRequest.getRestMethodName() + " " + elasticSearchRestUrl);

    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Iterator<Entry> it = clientRequest.getHeaders().entrySet().iterator(); it.hasNext();) {
            final Entry header = it.next();
            request.addHeader((String) header.getKey(), header.getValue().toString());
        }/*from   w w  w  .j  ava  2s  .c  o  m*/
    }

    final HttpResponse response = httpClient.execute(request);

    // If head method returns no content, it is added according to response code thanks to https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        if (response.getEntity() == null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
            }
        }
    }
    return new Tuple(deserializeResponse(response, clientRequest), response);
}

From source file:com.keydap.sparrow.SparrowClient.java

private <T> SearchResponse<T> sendSearchRequest(HttpUriRequest req, Class<T> resClas) {
    SearchResponse<T> result = new SearchResponse<T>();
    try {/*from   ww w.  j a  v a2  s .  c  om*/
        LOG.debug("Sending {} request to {}", req.getMethod(), req.getURI());
        authenticator.addHeaders(req);
        HttpResponse resp = client.execute(req);
        authenticator.saveHeaders(resp);
        StatusLine sl = resp.getStatusLine();
        int code = sl.getStatusCode();

        LOG.debug("Received status code {} from the request to {}", code, req.getURI());

        HttpEntity entity = resp.getEntity();
        String json = null;
        if (entity != null) {
            json = EntityUtils.toString(entity);
        }

        result.setHttpBody(json);
        result.setHttpCode(code);
        result.setHeaders(resp.getAllHeaders());

        // if it is success there will be response body to read
        if (code == 200) {
            if (json != null) { // DELETE will have no response body, so check for null

                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                JsonElement je = obj.get("totalResults");
                if (je != null) {
                    result.setTotalResults(je.getAsInt());
                }

                je = obj.get("startIndex");
                if (je != null) {
                    result.setStartIndex(je.getAsInt());
                }

                je = obj.get("itemsPerPage");
                if (je != null) {
                    result.setItemsPerPage(je.getAsInt());
                }

                je = obj.get("Resources"); // yes, the 'R' in resources must be upper case
                if (je != null) {
                    JsonArray arr = je.getAsJsonArray();
                    Iterator<JsonElement> itr = arr.iterator();
                    List<T> resources = new ArrayList<T>();
                    while (itr.hasNext()) {
                        JsonObject r = (JsonObject) itr.next();
                        if (resClas != null) {
                            resources.add(unmarshal(r, resClas));
                        } else {
                            T rsObj = unmarshal(r);
                            if (rsObj == null) {
                                LOG.warn(
                                        "No resgistered resource class found to deserialize the resource data {}",
                                        r);
                            } else {
                                resources.add(rsObj);
                            }
                        }
                    }

                    if (!resources.isEmpty()) {
                        result.setResources(resources);
                    }
                }
            }
        } else {
            if (json != null) {
                Error error = serializer.fromJson(json, Error.class);
                result.setError(error);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.warn("", e);
        result.setHttpCode(-1);
        Error err = new Error();

        err.setDetail(e.getMessage());
        result.setError(err);
    }
    return result;
}

From source file:org.fcrepo.apix.registry.impl.HttpRegistry.java

private CloseableHttpResponse execute(final HttpUriRequest request) {
    CloseableHttpResponse response = null;

    try {//from ww w . j  a v a 2s . c o  m
        response = client.execute(request);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    final int code = response.getStatusLine().getStatusCode();
    if (code != SC_OK) {
        try {
            if (code == SC_NOT_FOUND || code == SC_GONE) {
                throw new ResourceNotFoundException("HTTP " + code + ": " + request.getURI());
            }

            try {
                LOG.warn(IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF_8")));
            } catch (final Exception e) {
                LOG.warn(Integer.toString(response.getStatusLine().getStatusCode()));
            }
            throw new RuntimeException(String.format("Error performing %s on %s: %s; %s", request.getMethod(),
                    request.getURI(), response.getStatusLine(), body(response)));

        } finally {
            try {
                response.close();
            } catch (final IOException e) {
                // nothing
            }
        }
    }

    return response;
}

From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java

/**
 * Send an HTTP request to the remote site and process the returned HTTP
 * response This method://from  w w  w  .  j a  v a  2  s  .c o  m
 * <ul>
 * <li>creates an org.apache.http.HttpRequest</li>
 * <li>executes it using instances of HttpClient and HttpContext provides by
 * HttpClientResourceManager</li>
 * <li>converts the resulting org.apache.http.HttpResponse to a
 * fr.ippon.wip.http.Response</li>
 * </ul>
 * 
 * @param request
 *            Contains all the data needed to create an
 *            org.apache.http.HttpRequest
 * @param portletRequest
 *            Gives access to javax.portlet.PortletSession and windowID
 * @param portletResponse
 *            Used to create PortletURL if instance of MimeResponse
 * @return The returned Response instance can reference an InputStream
 *         linked to a connection from an HttpClient pool It necessary to
 *         call either Response#dispose, Response#printResponseContent or
 *         Response#sendResponse to release the underlying HTTP connection.
 * @throws IOException
 */
public Response execute(RequestBuilder request, PortletRequest portletRequest, PortletResponse portletResponse)
        throws IOException {
    if (WIPUtil.isDebugMode(portletRequest))
        WIPLogging.INSTANCE.logTransform(request.getRequestedURL());

    Response response = null;
    HttpResponse httpResponse = null;
    HttpEntity responseEntity = null;
    HttpClientResourceManager resourceManager = HttpClientResourceManager.getInstance();
    try {
        // Get Apache HttpComponents resources from ResourceManager
        HttpClient client = resourceManager.getHttpClient(portletRequest);
        HttpContext context = resourceManager.initExecutionContext(portletRequest, portletResponse, request);
        HttpUriRequest httpRequest;

        httpRequest = request.buildHttpRequest();

        // Execute the request
        try {
            httpResponse = client.execute(httpRequest, context);
            responseEntity = httpResponse.getEntity();

            // the HttpEntity content may be set as non repeatable, meaning it can be read only once
            byte[] responseBody = (responseEntity == null) ? null : EntityUtils.toByteArray(responseEntity);

            manageAuthentification(portletRequest, context, httpResponse);

            // what if the request was redirected? how to catch the last URL?
            String actualUrl = getActualUrl(portletRequest, context, request, httpResponse);

            // Create Response object from HttpResponse
            response = createResponse(httpResponse, responseBody, actualUrl,
                    portletResponse instanceof MimeResponse);

            StringBuffer buffer = new StringBuffer();
            buffer.append(httpRequest.getMethod() + " " + request.getRequestedURL() + " "
                    + httpResponse.getProtocolVersion() + "\" " + httpResponse.getStatusLine().getStatusCode());
            buffer.append("\n");
            for (Header header : httpResponse.getAllHeaders())
                buffer.append(header.getName() + " : " + header.getValue() + "\n");

            ACCESS_LOG.log(Level.INFO, buffer.toString());

            // logging if enabled
            if (WIPUtil.isDebugMode(portletRequest) && responseBody != null && !response.isBinary())
                WIPLogging.INSTANCE.logTransform(new String(responseBody) + "\n");

        } catch (RuntimeException rte) {
            throw rte;
        }

    } catch (URISyntaxException e) {
        LOG.log(Level.WARNING, "ERROR while creating URI", e);

    } finally {
        if (httpResponse != null && responseEntity != null)
            EntityUtils.consume(responseEntity);

        resourceManager.releaseThreadResources();
    }

    return response;
}

From source file:com.socialize.provider.BaseSocializeProvider.java

private ListResult<T> doListTypeRequest(HttpUriRequest request, ActionType type, boolean isJSONResponse)
        throws SocializeException {
    List<T> results = null;
    List<ActionError> errors = null;
    HttpEntity entity = null;//  w  w  w  .j ava 2  s. c  om

    ListResult<T> result = null;

    if (!clientFactory.isDestroyed()) {

        try {
            HttpClient client = clientFactory.getClient();

            if (logger != null && logger.isDebugEnabled()) {
                logger.debug("Request: " + request.getMethod() + " " + request.getRequestLine().getUri());
            }

            HttpResponse response = executeRequest(client, request);

            if (logger != null && logger.isDebugEnabled()) {
                logger.debug("RESPONSE CODE: " + response.getStatusLine().getStatusCode());
            }

            entity = response.getEntity();

            if (httpUtils.isHttpError(response)) {

                if (sessionPersister != null && httpUtils.isAuthError(response)) {
                    sessionPersister.delete(context.get());
                }

                String msg = ioUtils.readSafe(entity.getContent());
                throw new SocializeApiError(httpUtils, response.getStatusLine().getStatusCode(), msg);
            } else {

                result = new ListResult<T>();

                if (isJSONResponse) {
                    // Read the json just for logging
                    String json = ioUtils.readSafe(entity.getContent());

                    if (logger != null && logger.isDebugEnabled()) {
                        logger.debug("RESPONSE: " + json);
                    }

                    if (!StringUtils.isEmpty(json)) {

                        JSONObject object;

                        try {
                            object = jsonParser.parseObject(json);
                        } catch (JSONException je) {
                            throw new SocializeException("Failed to parse response as JSON [" + json + "]", je);
                        }

                        if (object.has(JSON_ATTR_ERRORS) && !object.isNull(JSON_ATTR_ERRORS)) {

                            JSONArray errorList = object.getJSONArray(JSON_ATTR_ERRORS);

                            int length = errorList.length();

                            errors = new ArrayList<ActionError>(length);

                            for (int i = 0; i < length; i++) {
                                JSONObject jsonObject = errorList.getJSONObject(i);
                                ActionError error = errorFactory.fromJSON(jsonObject);
                                errors.add(error);
                            }

                            result.setErrors(errors);
                        }

                        if (object.has(JSON_ATTR_ITEMS) && !object.isNull(JSON_ATTR_ITEMS)) {
                            JSONArray list = object.getJSONArray(JSON_ATTR_ITEMS);

                            int length = list.length();

                            results = new ArrayList<T>(length);

                            for (int i = 0; i < length; i++) {
                                results.add(fromJSON(list.getJSONObject(i), type));
                            }

                            result.setItems(results);
                        }

                        if (object.has(JSON_ATTR_COUNT) && !object.isNull(JSON_ATTR_COUNT)) {
                            result.setTotalCount(object.getInt(JSON_ATTR_COUNT));
                        }
                    }
                }
            }
        } catch (Throwable e) {
            throw SocializeException.wrap(e);
        } finally {
            closeEntity(entity);
        }

        return result;
    } else {
        if (logger != null) {
            logger.warn("Attempt to access HttpClientFactory that was already destroyed");
        }

        return null;
    }
}

From source file:net.officefloor.plugin.web.http.template.section.HttpTemplateSectionIntegrationTest.java

/**
 * Ensure maintain {@link HttpRequestState} across redirect.
 *///w w  w  . j ava  2s.  c o m
public void testPostRedirectGet_AlternateMethod() throws Exception {
    HttpUriRequest request = new HttpOther("http://" + HOST_NAME + ":" + this.httpPort + "/uri-post?text=TEST");
    this.doPostRedirectGetPatternTest(request, "TEST /uri-post",
            HttpTemplateInitialWorkSource.PROPERTY_RENDER_REDIRECT_HTTP_METHODS, request.getMethod());
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private void storeConnectionInfo(final HttpUriRequest httpUriRequest) {
    final int port = httpUriRequest.getURI().getPort();
    final String thost = httpUriRequest.getURI().getHost();
    //assert thost != null : "uri = " + httpUriRequest.getURI().toString();
    ConnectionInfo.addConnection(/*from  w w w.  j av a 2 s .  c  om*/
            new ConnectionInfo(httpUriRequest.getURI().getScheme(), port == -1 ? thost : thost + ":" + port,
                    httpUriRequest.getMethod() + " " + httpUriRequest.getURI().getPath(),
                    httpUriRequest.hashCode(), System.currentTimeMillis(), this.upbytes));
}