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

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:com.telefonica.iot.cosmos.hive.authprovider.OAuth2AuthenticationProviderImpl.java

@Override
public void Authenticate(String user, String token) throws AuthenticationException {
    // create the Http client
    HttpClient httpClient = httpClientFactory.getHttpClient(true);

    // create the request
    String url = idmEndpoint + "/user?access_token=" + token;
    HttpRequestBase request = new HttpGet(url);

    // do the request
    HttpResponse httpRes = null;//from   w w  w  .  j  a v a  2s .c  om

    try {
        httpRes = httpClient.execute(request);
        LOGGER.debug("Doing request: " + request.toString());
    } catch (IOException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // get the input streamResponse
    String streamResponse = "";

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
        streamResponse = reader.readLine();
        LOGGER.debug("Response received: " + streamResponse);
    } catch (IOException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // parse the input streamResponse as a Json
    JSONObject jsonResponse = null;

    try {
        JSONParser jsonParser = new JSONParser();
        jsonResponse = (JSONObject) jsonParser.parse(streamResponse);
    } catch (ParseException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // check if the given token does not exist
    if (jsonResponse.containsKey("error")) {
        throw new AuthenticationException("The given token does not exist");
    } // if

    // check if the obtained user id matches the given user
    if (jsonResponse.containsKey("id") && !jsonResponse.get("id").equals(user)) {
        throw new AuthenticationException("The given token does not match the given user");
    } // if

    // release the connection
    request.releaseConnection();

    LOGGER.debug("User " + user + " authenticated");
}

From source file:com.youzu.android.framework.http.SyncHttpHandler.java

public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {//from www .  ja  va 2s . c o m
            requestUrl = request.toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl + request.toString());
                if (result != null) {
                    return new ResponseStream(result);
                }
            }

            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}

From source file:org.sentilo.common.rest.impl.RESTClientImpl.java

private String executeHttpCall(final HttpRequestBase httpRequest, final String body, final String identityToken)
        throws RESTClientException {
    try {/*from   w  w w. j  a  v  a  2 s  . c om*/
        logger.debug("Executing http call {} ", httpRequest.toString());
        if (StringUtils.hasText(body)) {
            ((HttpEntityEnclosingRequestBase) httpRequest)
                    .setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        }

        if (StringUtils.hasText(identityToken)) {
            httpRequest.addHeader(RESTUtils.buildIdentityHeader(identityToken));
        }

        if (StringUtils.hasText(secretKey)) {
            addSignedHeader(httpRequest, body);
        }

        final HttpResponse response = httpClient.execute(httpRequest);
        validateResponse(response);
        return EntityUtils.toString(response.getEntity());
    } catch (final RESTClientException e) {
        throw e;
    } catch (final Exception e) {
        final String msg = String.format("Error while executing http call: %s ", httpRequest.toString());
        throw new RESTClientException(msg, e);
    }
}

From source file:com.youzu.android.framework.http.HttpHandler.java

private ResponseInfo<T> sendRequestForCache(HttpRequestBase request) {
    requestMethod = request.getMethod();

    boolean isEnableCache = com.youzu.android.framework.HttpUtils.sHttpCache.isEnabled(requestMethod);

    //        Log.e("APP", "requestMethod" + requestMethod + " isEnableCache:" + isEnableCache);

    if (isEnableCache) {
        String result = com.youzu.android.framework.HttpUtils.sHttpCache.get(requestUrl + request.toString());
        if (result != null) {
            return new ResponseInfo<T>(null, (T) result, true);
        }/*from  w ww .j  a v a 2 s  .  co  m*/
    }
    return null;
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANRequester.java

/**
 * Common method to perform HTTP request using the CKAN API with payload.
 * @param method HTTP method//  w ww .j a  va 2 s . com
 * @param urlPath URL path to be added to the base URL
 * @param payload Request payload
 * @return CKANResponse associated to the request
 * @throws Exception
 */
public CKANResponse doCKANRequest(String method, String urlPath, String payload) throws Exception {
    // build the final URL
    String url = baseURL + urlPath;

    HttpRequestBase request = null;
    HttpResponse response = null;

    try {
        // do the post
        if (method.equals("GET")) {
            request = new HttpGet(url);
        } else if (method.equals("POST")) {
            HttpPost r = new HttpPost(url);

            // payload (optional)
            if (!payload.equals("")) {
                logger.debug("request payload: " + payload);
                r.setEntity(new StringEntity(payload, ContentType.create("application/json")));
            } // if

            request = r;
        } else {
            throw new CygnusRuntimeError("HTTP method not supported: " + method);
        } // if else

        // headers
        request.addHeader("Authorization", apiKey);

        // execute the request
        logger.debug("CKAN operation: " + request.toString());
    } catch (Exception e) {
        if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError
                || e instanceof CygnusBadConfiguration) {
            throw e;
        } else {
            throw new CygnusRuntimeError(e.getMessage());
        } // if else
    } // try catch

    try {
        response = httpClient.execute(request);
    } catch (Exception e) {
        throw new CygnusPersistenceError(e.getMessage());
    } // try catch

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String res = reader.readLine();
        request.releaseConnection();
        long l = response.getEntity().getContentLength();
        logger.debug("CKAN response (" + l + " bytes): " + response.getStatusLine().toString());

        // get the JSON encapsulated in the response
        logger.debug("response payload: " + res);
        JSONParser j = new JSONParser();
        JSONObject o = (JSONObject) j.parse(res);

        // return result
        return new CKANResponse(o, response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError
                || e instanceof CygnusBadConfiguration) {
            throw e;
        } else {
            throw new CygnusRuntimeError(e.getMessage());
        } // if else
    } // try catch
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.hdfs.HDFSBackendImpl.java

private HttpResponse doHDFSRequest(HttpClient httpClient, String method, String url, ArrayList<Header> headers,
        StringEntity entity) throws Exception {
    HttpResponse response = null;//from  w ww .  j  a v a  2  s .c  o m
    HttpRequestBase request = null;

    if (method.equals("PUT")) {
        HttpPut req = new HttpPut(url);

        if (entity != null) {
            req.setEntity(entity);
        } // if

        request = req;
    } else if (method.equals("POST")) {
        HttpPost req = new HttpPost(url);

        if (entity != null) {
            req.setEntity(entity);
        } // if

        request = req;
    } else if (method.equals("GET")) {
        request = new HttpGet(url);
    } else {
        throw new CygnusRuntimeError("HTTP method not supported: " + method);
    } // if else

    if (headers != null) {
        for (Header header : headers) {
            request.setHeader(header);
        } // for
    } // if

    logger.debug("HDFS request: " + request.toString());

    try {
        response = httpClient.execute(request);
    } catch (IOException e) {
        throw new CygnusPersistenceError(e.getMessage());
    } // try catch

    request.releaseConnection();
    logger.debug("HDFS response: " + response.getStatusLine().toString());
    return response;
}

From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java

/**
 * Common method to perform HTTP requests using the CKAN API with payload.
 * @param method HTTP method// w w  w  .ja v  a  2 s  . co m
 * @param url URL path to be added to the base URL
 * @param payload Request payload
 * @return CKANResponse associated to the request
 * @throws Exception
 */
public CKANResponse doCKANRequest(String method, String url, String payload) throws Exception {
    HttpRequestBase request = null;
    HttpResponse response = null;

    try {
        // do the post
        if (method.equals("GET")) {
            request = new HttpGet(url);
        } else if (method.equals("POST")) {
            HttpPost r = new HttpPost(url);

            // payload (optional)
            if (!payload.equals("")) {
                logger.debug("request payload: " + payload);
                r.setEntity(new StringEntity(payload, ContentType.create("application/json")));
            } // if

            request = r;
        } else {
            throw new Exception("HTTP method not supported: " + method);
        } // if else

        // headers
        request.addHeader("Authorization", apiKey);

        // execute the request
        logger.debug("CKAN operation: " + request.toString());
    } catch (Exception e) {
        throw e;
    } // try catch

    try {
        response = httpClientFactory.getHttpClient(ssl).execute(request);
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    } // try catch

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String res = "";
        String line;

        while ((line = reader.readLine()) != null) {
            res += line;
        } // while

        request.releaseConnection();
        long l = response.getEntity().getContentLength();
        logger.debug("CKAN response (" + l + " bytes): " + response.getStatusLine().toString());

        // get the JSON encapsulated in the response
        logger.debug("response payload: " + res);
        JSONParser j = new JSONParser();
        JSONObject o = (JSONObject) j.parse(res);

        // return result
        return new CKANResponse(o, response.getStatusLine().getStatusCode());
    } catch (IOException e) {
        throw e;
    } catch (IllegalStateException e) {
        throw e;
    } catch (ParseException e) {
        throw e;
    } // try catch
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackend.java

/**
 * Does a Http request given a method, a relative URL, a list of headers and
 * the payload Protected method due to it's used by the tests.
 * /*from www  .java2 s. c o  m*/
 * @param method
 * @param url
 * @param headers
 * @param entity
 * @return The result of the request
 * @throws CygnusRuntimeError
 * @throws CygnusPersistenceError
 */

protected JsonResponse doRequest(String method, String url, ArrayList<Header> headers, StringEntity entity)
        throws CygnusRuntimeError, CygnusPersistenceError {
    HttpResponse httpRes = null;
    HttpRequestBase request;

    switch (method) {

    case "PUT":
        HttpPut reqPut = new HttpPut(url);

        if (entity != null) {
            reqPut.setEntity(entity);
        } // if

        request = reqPut;
        break;
    case "POST":
        HttpPost reqPost = new HttpPost(url);

        if (entity != null) {
            reqPost.setEntity(entity);
        } // if

        request = reqPost;
        break;
    case "GET":
        request = new HttpGet(url);
        break;
    case "DELETE":
        request = new HttpDelete(url);
        break;
    default:
        throw new CygnusRuntimeError("Http '" + method + "' method not supported");
    } // switch

    if (headers != null) {
        for (Header header : headers) {
            request.setHeader(header);
        } // for
    } // if

    LOGGER.debug("Http request: " + request.toString());

    try {
        httpRes = httpClient.execute(request);
    } catch (IOException e) {
        request.releaseConnection();
        throw new CygnusPersistenceError("Request error", "IOException", e.getMessage());
    } // try catch

    JsonResponse response = createJsonResponse(httpRes);
    request.releaseConnection();
    return response;
}

From source file:org.openo.sdnhub.overlayvpndriver.http.OverlayVpnDriverSsoProxy.java

@SuppressWarnings("deprecation")
private HTTPReturnMessage commonRequest(HttpRequestBase requestBase) {
    HTTPReturnMessage msg = new HTTPReturnMessage();
    msg.setStatus(FAILED);/*from  ww w  . j  a  v a 2  s . co m*/
    if (!isParamValide()) {
        LOGGER.warn("AC Login commonRequest is inValide, Login failed.");
        return msg;
    }

    requestBase.addHeader("Content-Type", APPLICATION_JSON);
    requestBase.addHeader("Accept", APPLICATION_JSON);

    try {
        LOGGER.info(requestBase.toString());
        HttpResponse resp = httpClient.execute(requestBase);
        LOGGER.info(resp.toString());

        String respContent = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
        LOGGER.debug("Response status : " + resp.getStatusLine().getStatusCode());
        LOGGER.debug("Response body : " + respContent);

        msg.setBody(respContent);
        msg.setStatus(resp.getStatusLine().getStatusCode());
        this.release(resp);
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Do Post Request Failed.", e);
    } catch (ClientProtocolException e) {
        LOGGER.warn("Do Post Request Failed.", e);
    } catch (ParseException e) {
        LOGGER.warn("Do Post Request Failed.", e);
    } catch (IOException e) {
        LOGGER.warn("Do Post Request Failed.", e);
    } catch (IllegalStateException e) {
        LOGGER.warn("Do Post Request Failed.", e);
    }

    return msg;
}