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

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

Introduction

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

Prototype

public abstract String getMethod();

Source Link

Usage

From source file:io.adventurous.android.api.ApiHttpClient.java

public static HttpResponse execute(HttpRequestBase request, ApiCredentials credentials, String deviceId)
        throws IOException {
    MyLog.d(TAG, request.getMethod() + ": " + request.getURI());
    setApiCredentials(credentials, request);
    setDeviceIdHeader(request, deviceId);

    long start = System.currentTimeMillis();
    HttpResponse response = mClient.execute(request);
    long end = System.currentTimeMillis();
    MyLog.d(TAG, request.getMethod() + ": " + request.getURI() + " - took " + (end - start) + "ms");
    return response;
}

From source file:com.kolich.havalo.client.service.HavaloClientSigner.java

private static final String getStringToSign(final HttpRequestBase request) {
    final StringBuilder sb = new StringBuilder();
    // HTTP-Verb (GET, PUT, POST, or DELETE) + "\n"
    sb.append(request.getMethod().toUpperCase()).append(LINE_SEPARATOR_UNIX);
    // RFC822 formatted Date (from 'Date' header on request) + "\n"      
    sb.append(request.getFirstHeader(DATE).getValue()).append(LINE_SEPARATOR_UNIX);
    // Content-Type (from 'Content-Type' request header, optional) + "\n"
    final Header contentType;
    if ((contentType = request.getFirstHeader(CONTENT_TYPE)) != null) {
        sb.append(contentType.getValue());
    }/*w  w  w  .  j a v  a  2s.  co m*/
    sb.append(LINE_SEPARATOR_UNIX);
    // CanonicalizedResource
    sb.append(request.getURI().getRawPath());
    return sb.toString();
}

From source file:gov.nasa.ensemble.common.http.HttpUtils.java

public static void consume(HttpRequestBase request, HttpResponse response) throws IOException {
    if (response != null) {
        try {/* ww  w  .j  a  v  a2  s  .  c o m*/
            EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            if (request != null) {
                throw new IOException("releasing entity for " + request.getMethod(), e);
            } else {
                throw new IOException("releasing entity", e);
            }
        }
    }
}

From source file:org.bedework.util.http.HttpUtil.java

/** Send content
 *
 * @param content the content as bytes/*from  ww  w  .  j a  va  2  s  .  c  o  m*/
 * @param contentType its type
 * @throws HttpException if not entity enclosing request
 */
public static void setContent(final HttpRequestBase req, final byte[] content, final String contentType)
        throws HttpException {
    if (content == null) {
        return;
    }

    if (!(req instanceof HttpEntityEnclosingRequestBase)) {
        throw new HttpException("Invalid operation for method " + req.getMethod());
    }

    final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) req;

    final ByteArrayEntity entity = new ByteArrayEntity(content);
    entity.setContentType(contentType);
    eem.setEntity(entity);
}

From source file:com.smartsheet.api.internal.http.RequestAndResponseData.java

/**
 * factory method for creating a RequestAndResponseData object from request and response data with the specifid trace fields
 *///from w  w  w .  j a  va  2  s  .c  om
public static RequestAndResponseData of(HttpRequestBase request, HttpEntitySnapshot requestEntity,
        HttpResponse response, HttpEntitySnapshot responseEntity, Set<Trace> traces) throws IOException {
    RequestData.Builder requestBuilder = new RequestData.Builder();
    ResponseData.Builder responseBuilder = new ResponseData.Builder();

    if (request != null) {
        requestBuilder.withCommand(request.getMethod() + " " + request.getURI());
        boolean binaryBody = false;
        if (traces.contains(Trace.RequestHeaders) && request.getAllHeaders() != null) {
            requestBuilder.withHeaders();
            for (Header header : request.getAllHeaders()) {
                String headerName = header.getName();
                String headerValue = header.getValue();
                if ("Authorization".equals(headerName) && headerValue.length() > 0) {
                    headerValue = "Bearer ****" + headerValue.substring(Math.max(0, headerValue.length() - 4));
                } else if ("Content-Disposition".equals(headerName)) {
                    binaryBody = true;
                }
                requestBuilder.addHeader(headerName, headerValue);
            }
        }
        if (requestEntity != null) {
            if (traces.contains(Trace.RequestBody)) {
                requestBuilder
                        .setBody(binaryBody ? binaryBody(requestEntity) : getContentAsText(requestEntity));
            } else if (traces.contains(Trace.RequestBodySummary)) {
                requestBuilder.setBody(binaryBody ? binaryBody(requestEntity)
                        : truncateAsNeeded(getContentAsText(requestEntity), TRUNCATE_LENGTH));
            }
        }
    }
    if (response != null) {
        boolean binaryBody = false;
        responseBuilder.withStatus(response.getStatusText());
        if (traces.contains(Trace.ResponseHeaders) && response.getHeaders() != null) {
            responseBuilder.withHeaders();
            for (Map.Entry<String, String> header : response.getHeaders().entrySet()) {
                String headerName = header.getKey();
                String headerValue = header.getValue();
                if ("Content-Disposition".equals(headerName)) {
                    binaryBody = true;
                }
                responseBuilder.addHeader(headerName, headerValue);
            }
        }
        if (responseEntity != null) {
            if (traces.contains(Trace.ResponseBody)) {
                responseBuilder
                        .setBody(binaryBody ? binaryBody(responseEntity) : getContentAsText(responseEntity));
            } else if (traces.contains(Trace.ResponseBodySummary)) {
                responseBuilder.setBody(binaryBody ? binaryBody(responseEntity)
                        : truncateAsNeeded(getContentAsText(responseEntity), TRUNCATE_LENGTH));
            }
        }
    }
    return new RequestAndResponseData(requestBuilder.build(), responseBuilder.build());
}

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static void print(HttpRequestBase httpMethod) {
    Logger.debug(httpMethod.getMethod(), httpMethod.getRequestLine().toString());

    Header[] headers = httpMethod.getAllHeaders();
    for (Header header : headers) {
        Logger.debug("headers", header.toString());
    }/*w  w w .  j  a  v  a 2s  . c  om*/
}

From source file:com.hdsfed.cometapi.ThreadTrackerDB.java

static private synchronized int HttpCatchError(HttpRequestBase httpRequest, HttpResponse httpResponse)
        throws IOException {
    if (2 != (int) (httpResponse.getStatusLine().getStatusCode() / 100)) {
        // Clean up after ourselves and release the HTTP connection to the connection manager.
        EntityUtils.consume(httpResponse.getEntity());
        //ScreenLog.out(Headers,"BEGIN header dump");
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                "Unexpected status returned from " + httpRequest.getMethod() + " ("
                        + httpResponse.getStatusLine().getStatusCode() + ": "
                        + httpResponse.getStatusLine().getReasonPhrase() + ")");
    }//from   w w  w. j  a  va2  s  .  c o m
    return (int) (httpResponse.getStatusLine().getStatusCode());
}

From source file:org.wso2.carbon.appmgt.mdm.restconnector.utils.RestUtils.java

/**
 * Execute HTTP method and return whether operation success or not.
 *
 * @param remoteServer Bean that holds information about remote server
 * @param httpClient HTTP client object//from   w ww  . j  a v  a  2 s .  c  o  m
 * @param httpRequestBase HTTP method which should be executed
 * @return true if HTTP method successfully executed false if not
 */
public static String executeMethod(RemoteServer remoteServer, HttpClient httpClient,
        HttpRequestBase httpRequestBase) {
    String authKey = getAPIToken(remoteServer, false);
    HttpResponse response = null;
    String responseString = null;
    if (log.isDebugEnabled()) {
        log.debug("Access token received : " + authKey);
    }

    try {
        int statusCode = 401;
        int tries = 0;
        while (statusCode != 200) {

            if (log.isDebugEnabled()) {
                log.debug("Trying to call API : trying for " + (tries + 1) + " time(s).");
            }

            httpRequestBase.setHeader(Constants.RestConstants.AUTHORIZATION,
                    Constants.RestConstants.BEARER + authKey);
            if (log.isDebugEnabled()) {
                log.debug("Sending " + httpRequestBase.getMethod() + " request to " + httpRequestBase.getURI());
            }

            response = httpClient.execute(httpRequestBase);
            statusCode = response.getStatusLine().getStatusCode();
            if (log.isDebugEnabled()) {
                log.debug("Status code received : " + statusCode);
            }

            if (++tries >= 3) {
                log.info("API Call failed for the 3rd time: No or Unauthorized Access Aborting.");
                return null;
            }
            if (statusCode == 401) {
                authKey = getAPIToken(remoteServer, true);
                if (log.isDebugEnabled()) {
                    log.debug("Access token getting again, Access token received :  " + authKey + " in  try "
                            + tries + ".");
                }
            }
        }
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            responseString = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        }
        return responseString;
    } catch (IOException e) {
        String errorMessage = "No OK response received form the API.";
        log.error(errorMessage, e);
        return null;
    }
}

From source file:org.elasticsearch.client.RestClient.java

private static HttpRequestBase addRequestBody(HttpRequestBase httpRequest, HttpEntity entity) {
    if (entity != null) {
        if (httpRequest instanceof HttpEntityEnclosingRequestBase) {
            ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity);
        } else {//from w  w  w .jav  a 2 s  .c om
            throw new UnsupportedOperationException(httpRequest.getMethod() + " with body is not supported");
        }
    }
    return httpRequest;
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Print the HTTP request - for debugging purposes
 *//*from   ww  w .j av  a 2 s.c o  m*/
@SuppressWarnings("unused")
private static void printRequest(HttpRequestBase request) {
    if (LOGGER.isLoggable(Level.FINER)) {
        StringBuffer logMessage = new StringBuffer();
        logMessage.append(NEW_LINE).append("\t- Method: ").append(request.getMethod()); //$NON-NLS-1$ //
        logMessage.append(NEW_LINE).append("\t- URL: ").append(request.getURI()); //$NON-NLS-1$
        logMessage.append(NEW_LINE).append("\t- Headers: "); //$NON-NLS-1$
        Header[] headers = request.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            logMessage.append(NEW_LINE).append("\t\t- ").append(headers[i].getName()).append(": ") //$NON-NLS-1$//$NON-NLS-2$
                    .append(headers[i].getValue());
        }
        LOGGER.finer(logMessage.toString());
    }
}