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

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:it.restrung.rest.client.DefaultRestClientImpl.java

/**
 * Performs a DELETE request to the given url
 *
 * @param url      the url/*from   w w w  .  java  2 s.  c o m*/
 * @param user     an optional user for basic auth
 * @param password an optional password for basic auth
 * @param body     the requests body if any
 * @param timeout  the request timeout
 * @param delegate the api delegate that will receive callbacks regarding progress and results   @return the response body as a string
 * @throws APIException
 */
public static String performDelete(String url, String user, String password, JSONSerializable body, int timeout,
        APIDelegate<?> delegate) throws APIException {
    Log.d(RestClient.class.getSimpleName(), "DELETE: " + url);
    String responseBody;
    try {
        DefaultHttpClient httpclient = HttpClientFactory.getClient();
        HttpRequestBase httpDelete = body == null ? new HttpDelete(url) : new HttpDeleteWithBody(url);
        setupTimeout(timeout, httpclient);
        setupCommonHeaders(httpDelete);
        setupBasicAuth(user, password, httpDelete);
        if (body != null && HttpEntityEnclosingRequestBase.class.isAssignableFrom(httpDelete.getClass())) {
            setupRequestBody((HttpEntityEnclosingRequestBase) httpDelete, body.toJSON(), null, null);
        }
        handleRequest(httpDelete, delegate);
        HttpResponse response = httpclient.execute(httpDelete);
        responseBody = handleResponse(response, delegate);
    } catch (ClientProtocolException e) {
        throw new APIException(e, APIException.UNTRACKED_ERROR);
    } catch (IOException e) {
        throw new APIException(e, APIException.UNTRACKED_ERROR);
    }
    return responseBody;
}

From source file:org.wrml.runtime.service.rest.RestService.java

private HttpResponse executeRequest(final HttpRequestBase request) {

    LOG.debug("Making outgoing request {}", request);

    final HttpResponse response;
    try {/*from   w  w  w . j  av a 2 s . co m*/
        response = _HttpClient.execute(request);
    } catch (final IOException e) {
        LOG.error(
                "Failed to execute HTTP request: " + request.getClass().toString() + " to " + request.getURI(),
                e);
        throw new ServiceException("Failed to execute HTTP PUT request.", e, this);
    }

    LOG.debug("Received status code: {} in response to update request.",
            response.getStatusLine() != null ? response.getStatusLine().getStatusCode() : "NULL");

    if (response.getStatusLine().getStatusCode() / 100 != 2) {
        // Anything in the 300, 400, or 500 ranges will go here

        final String errorMessage = "Error: (" + response.getStatusLine().getStatusCode() + ") - "
                + request.getURI() + "\n" + response.getStatusLine().getReasonPhrase();
        LOG.error(errorMessage);

        throw new ServiceException(errorMessage, null, this);
    }

    return response;

}

From source file:eu.prestoprime.p4gui.connection.P4HttpClient.java

public HttpResponse executeRequest(HttpRequestBase request) throws IOException {
    // set userID
    request.setHeader(new BasicHeader("userID", this.userID));

    // disable redirect handling
    HttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    request.setParams(params);/*ww  w  .  j a  va  2s  . c  o  m*/

    // execute request
    HttpResponse response = super.execute(request);

    // check redirect
    if (redirectCodes.contains(response.getStatusLine().getStatusCode())) {
        logger.debug("Redirecting...");

        // get newURL
        String newURL = response.getFirstHeader("Location").getValue();

        // create newRequest
        try {
            HttpUriRequest newRequest = request.getClass().getDeclaredConstructor(String.class)
                    .newInstance(newURL);

            // copy entity
            if (request instanceof HttpEntityEnclosingRequestBase) {
                HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity();
                if (entity != null) {
                    logger.debug("Cloning entity...");

                    ((HttpEntityEnclosingRequestBase) newRequest).setEntity(entity);
                }
            }

            // set userID
            newRequest.setHeader(new BasicHeader("userID", this.userID));

            // retry
            response = new P4HttpClient(userID).execute(newRequest);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException
                | InstantiationException e) {
            e.printStackTrace();
        }
    }

    return response;
}

From source file:nl.esciencecenter.ptk.web.WebClient.java

/**
 * Execute Put or Post method and handle the (optional) String response.
 * Returns actual HTTP Status. Method does not do any (http) response status
 * handling. If the Put method succeeded but the HTTP status != 200 then
 * this value is returned and no Exception is thrown.
 * /* w  ww  . j a va 2 s. co  m*/
 * @param putOrPostmethod
 *            - HttpPut or HttpPost method to execute
 * @param responseTextHolder
 *            - Optional StringHolder for the Response: Put and Post might
 *            nor return any response.
 * @param contentTypeHolder
 *            - Optional StringHolder for the contentType (mimeType).
 * 
 * @return actual HTTP Status as returned by server.
 * @throws WebException
 *             if a communication error occurred.
 */
protected int executeAuthenticatedPut(HttpRequestBase putOrPostmethod, StringHolder responseTextHolder,
        StringHolder contentTypeHolder) throws WebException {
    if (this.httpClient == null) {
        throw new NullPointerException("HTTP Client not properly initialized: httpClient==null");
    }

    logger.debugPrintf("executePutOrPost():'%s'\n", putOrPostmethod.getRequestLine());

    boolean isPut = (putOrPostmethod instanceof HttpPut);
    boolean isPost = (putOrPostmethod instanceof HttpPost);

    if ((isPut == false) && (isPost == false)) {
        throw new IllegalArgumentException(
                "Method class must be either HttpPut or HttpPost. Class=" + putOrPostmethod.getClass());
    }

    String actualUser;

    try {
        HttpResponse response;

        if (config.getUseBasicAuthentication()) {
            actualUser = config.getUsername();
            String passwdStr = new String(config.getPasswordChars());
            logger.debugPrintf("Using basic authentication, user=%s\n", actualUser);

            Header authHeader = new BasicHeader("Authorization",
                    "Basic " + (StringUtil.base64Encode((actualUser + ":" + passwdStr).getBytes())));
            putOrPostmethod.addHeader(authHeader);
        }

        response = httpClient.execute(putOrPostmethod);

        int status = handleStringResponse("executePutOrPost():" + putOrPostmethod.getRequestLine(), response,
                responseTextHolder, contentTypeHolder);

        this.lastHttpStatus = status;
        return status;
    } catch (ClientProtocolException e) {
        if ((config.getPort() == 443) && config.isHTTP()) {
            throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION,
                    "HTTP Protocol error: Trying to speak plain http to (SSL) port 443?\n" + e.getMessage(), e);
        } else if (config.isHTTPS()) {
            throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION,
                    "HTTPS Protocol error:" + e.getMessage(), e);
        } else {
            throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION,
                    "HTTP Protocol error:" + e.getMessage(), e);
        }

    } catch (javax.net.ssl.SSLPeerUnverifiedException e) {
        throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION,
                "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n"
                        + e.getMessage(),
                e);
    } catch (javax.net.ssl.SSLException e) {
        // Super class
        throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION,
                "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n"
                        + e.getMessage(),
                e);
    } catch (java.net.NoRouteToHostException e) {
        throw new WebException(WebException.Reason.NO_ROUTE_TO_HOST_EXCEPTION,
                "No route to host: Server could be down or unreachable.\n" + e.getMessage(), e);
    } catch (IOException e) {
        throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e);
    }
}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

private HttpRequestBase buildRequest(String httpMethod, String requestPath, Object entityContent)
        throws ScalewayApiException {
    LOGGER.debug("Building request for method '{}' and URL '{}'", httpMethod, requestPath);

    HttpRequestBase request = null;
    switch (httpMethod) {
    case Constants.HTTP_METHOD_GET:
        request = new HttpGet(requestPath);
        break;//  w w  w. j  ava  2s .  c  o  m
    case Constants.HTTP_METHOD_POST:
        request = new HttpPost(requestPath);
        break;
    case Constants.HTTP_METHOD_DELETE:
        request = new HttpDelete(requestPath);
        break;
    case Constants.HTTP_METHOD_PATCH:
        request = new HttpPatch(requestPath);
        break;
    case Constants.HTTP_METHOD_PUT:
        request = new HttpPut(requestPath);
        break;
    }

    request.setHeader(Constants.HEADER_KEY_AUTH_TOKEN, accessToken);
    request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.HEADER_VALUE_JSON_APPLICATION);

    if (null != entityContent) {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            try {
                StringEntity entity = new StringEntity(serializeObject(entityContent));
                ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
            } catch (UnsupportedEncodingException | JsonProcessingException ex) {
                throw new ScalewayApiException(ex);
            }
        } else {
            LOGGER.error("Attempting to set entity on non applicable base class of '{}'", request.getClass());
        }
    }
    return request;
}