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

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

Introduction

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

Prototype

void addHeader(String str, String str2);

Source Link

Usage

From source file:illab.nabal.proxy.TwitterContext.java

/**
 * Get OAuth-1.0a-ready HTTP request for test use only.
 * /*  w w  w .  j a v a 2  s . c  o m*/
 * @param httpMethod POST or GET
 * @param apiFullUrl
 * @param params
 * @param additionalOAuthParams
 * @param isAuthorizationCall true if the current request is a part of 
 *       OAuth authorization process
 * @return HttpUriRequest HttpPost or HttpGet
 * @throws Exception
 */
private HttpUriRequest getOAuthRequestBase(String httpMethod, String apiFullUrl, List<NameValuePair> params,
        List<NameValuePair> additionalOAuthParams, boolean isAuthorizationCall) throws Exception {

    HttpUriRequest httpRequest = null;

    // set OAuth parameters
    List<NameValuePair> oauthParams = ParameterHelper.addAllParams(
            // since Twitter checks timestamp in seconds, nonce should be GUARANTEED to be unique
            new BasicNameValuePair(OAUTH_NONCE, getSuperNonce()),
            new BasicNameValuePair(OAUTH_TIMESTAMP, getTimestamp()),
            new BasicNameValuePair(OAUTH_CONSUMER_KEY, mConsumerKey),
            new BasicNameValuePair(OAUTH_SIGNATURE_METHOD, HMAC_SHA1),
            new BasicNameValuePair(OAUTH_VERSION, OAUTH_VESION_1_0));

    // add additional OAuth parameters if exist
    if (additionalOAuthParams != null && additionalOAuthParams.size() > 0) {
        oauthParams.addAll(additionalOAuthParams);
    }

    // generate OAuth signature base string
    List<NameValuePair> baseStringParams = new ArrayList<NameValuePair>();
    baseStringParams.addAll(oauthParams);
    if (params != null && params.size() > 0) {
        baseStringParams.addAll(params);
    }
    String baseString = getBaseString(httpMethod, apiFullUrl, baseStringParams);

    // generate Authorization header string 
    String headerString = getOAuthHeaderString(
            ParameterHelper.addSignature(getSecretKey(), baseString, oauthParams));

    Log.d(TAG, "headerString : " + headerString);

    // add POST parameters to request body
    if (POST.equals(httpMethod)) {
        httpRequest = new HttpPost(new URI(apiFullUrl));
        if (params != null && params.size() > 0) {
            ((HttpPost) httpRequest)
                    .setEntity(new UrlEncodedFormEntity(params, org.apache.http.protocol.HTTP.UTF_8));
        }
    }

    // add GET query strings
    else if (GET.equals(httpMethod)) {
        String paramString = "";
        if (params != null && params.size() > 0) {
            paramString = "?" + URLEncodedUtils.format(params, org.apache.http.protocol.HTTP.UTF_8);
        }
        httpRequest = new HttpGet(new URI(apiFullUrl + paramString));
    }

    // add Authorization header to request header
    httpRequest.addHeader(AUTHORIZATION, headerString);

    // return HTTP request
    return httpRequest;
}

From source file:org.eclipse.om2m.binding.http.RestHttpClient.java

/**
 * Converts a protocol-independent {@link RequestPrimitive} object into a standard HTTP request and sends a standard HTTP request.
 * Converts the received standard HTTP request into {@link ResponsePrimitive} object and returns it back.
 * @param requestPrimitive - protocol independent request.
 * @return protocol independent response.
 *//*from  w  ww  .ja  v a2s  . c o m*/
public ResponsePrimitive sendRequest(RequestPrimitive requestPrimitive) {
    LOGGER.info("Sending request: " + requestPrimitive);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponsePrimitive responsePrimitive = new ResponsePrimitive(requestPrimitive);
    HttpUriRequest method = null;

    // Retrieve the url
    String url = requestPrimitive.getTo();
    if (!url.startsWith(protocol + "://")) {
        if (url.startsWith("://")) {
            url = protocol + url;
        } else if (url.startsWith("//")) {
            url = protocol + ":" + url;
        } else {
            url = protocol + "://" + url;
        }
    }

    Map<String, List<String>> parameters = getParameters(requestPrimitive);
    parameters.putAll(requestPrimitive.getQueryStrings());
    if (!parameters.isEmpty()) {
        String queryString = "";
        for (String parameter : parameters.keySet()) {
            for (String value : parameters.get(parameter)) {
                queryString += "&" + parameter + "=" + value;
            }
        }
        queryString = queryString.replaceFirst("&", "?");
        LOGGER.info("Query string generated: " + queryString);
        url += queryString;
    }

    try {
        // Set the operation
        BigInteger operation = requestPrimitive.getOperation();
        if (operation != null) {
            if (operation.equals(Operation.CREATE)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.RETRIEVE)) {
                method = new HttpGet(url);
            } else if (operation.equals(Operation.UPDATE)) {
                method = new HttpPut(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPut) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.DELETE)) {
                method = new HttpDelete(url);
            } else if (operation.equals(Operation.NOTIFY)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            }
        } else {
            return null;
        }

        // Set the return content type
        method.addHeader(HttpHeaders.ACCEPT, requestPrimitive.getReturnContentType());

        // Set the request content type
        String contentTypeHeader = requestPrimitive.getRequestContentType();

        // Set the request identifier header
        if (requestPrimitive.getRequestIdentifier() != null) {
            method.addHeader(HttpHeaders.REQUEST_IDENTIFIER, requestPrimitive.getRequestIdentifier());
        }

        // Set the originator header
        if (requestPrimitive.getFrom() != null) {
            method.addHeader(HttpHeaders.ORIGINATOR, requestPrimitive.getFrom());
        }

        // Add the content type header with the resource type for create operation
        if (requestPrimitive.getResourceType() != null) {
            contentTypeHeader += ";ty=" + requestPrimitive.getResourceType().toString();
        }
        method.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeHeader);

        // Add the notification URI in the case of non-blocking request
        if (requestPrimitive.getResponseTypeInfo() != null) {
            String uris = "";
            for (String notifUri : requestPrimitive.getResponseTypeInfo().getNotificationURI()) {
                uris += "&" + notifUri;
            }
            uris = uris.replaceFirst("&", "");
            method.addHeader(HttpHeaders.RESPONSE_TYPE, uris);
        }

        if (requestPrimitive.getName() != null) {
            method.addHeader(HttpHeaders.NAME, requestPrimitive.getName());
        }

        LOGGER.info("Request to be send: " + method.toString());
        String headers = "";
        for (Header h : method.getAllHeaders()) {
            headers += h.toString() + "\n";
        }
        LOGGER.info("Headers:\n" + headers);

        HttpResponse httpResponse = httpClient.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE) != null) {
            responsePrimitive.setResponseStatusCode(
                    new BigInteger(httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE).getValue()));
        } else {
            responsePrimitive.setResponseStatusCode(getResponseStatusCode(httpResponse, statusCode));
        }
        if (statusCode != 204) {
            if (httpResponse.getEntity() != null) {
                responsePrimitive.setContent(Util.convertStreamToString(httpResponse.getEntity().getContent()));
                if (httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null) {
                    responsePrimitive
                            .setContentType(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                }
            }
        }
        if (statusCode == 201) {
            String contentHeader = "";
            for (Header header : httpResponse.getHeaders(HttpHeaders.CONTENT_LOCATION)) {
                contentHeader += header.getValue();
            }
            responsePrimitive.setLocation(contentHeader);
        }
        LOGGER.info("Http Client response: " + responsePrimitive);
        httpClient.close();
    } catch (HttpHostConnectException e) {
        LOGGER.info("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
        responsePrimitive.setContent("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setContentType(MimeMediaType.TEXT_PLAIN);
    } catch (IOException e) {
        LOGGER.error(url + " not found", e);
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
    }
    return responsePrimitive;
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java

public HttpResponse fetch(org.apache.shindig.gadgets.http.HttpRequest request) throws GadgetException {
    HttpUriRequest httpMethod = null;/*  w  w w  .  j a v  a  2s .  c o  m*/
    Preconditions.checkNotNull(request);
    final String methodType = request.getMethod();

    final org.apache.http.HttpResponse response;
    final long started = System.currentTimeMillis();

    // Break the request Uri to its components:
    Uri uri = request.getUri();
    if (StringUtils.isEmpty(uri.getAuthority())) {
        throw new GadgetException(GadgetException.Code.INVALID_USER_DATA,
                "Missing domain name for request: " + uri, HttpServletResponse.SC_BAD_REQUEST);
    }
    if (StringUtils.isEmpty(uri.getScheme())) {
        throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Missing schema for request: " + uri,
                HttpServletResponse.SC_BAD_REQUEST);
    }
    String[] hostparts = StringUtils.splitPreserveAllTokens(uri.getAuthority(), ':');
    int port = -1; // default port
    if (hostparts.length > 2) {
        throw new GadgetException(GadgetException.Code.INVALID_USER_DATA,
                "Bad host name in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST);
    }
    if (hostparts.length == 2) {
        try {
            port = Integer.parseInt(hostparts[1]);
        } catch (NumberFormatException e) {
            throw new GadgetException(GadgetException.Code.INVALID_USER_DATA,
                    "Bad port number in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    String requestUri = uri.getPath();
    // Treat path as / if set as null.
    if (uri.getPath() == null) {
        requestUri = "/";
    }
    if (uri.getQuery() != null) {
        requestUri += '?' + uri.getQuery();
    }

    // Get the http host to connect to.
    HttpHost host = new HttpHost(hostparts[0], port, uri.getScheme());

    try {
        if ("POST".equals(methodType) || "PUT".equals(methodType)) {
            HttpEntityEnclosingRequestBase enclosingMethod = ("POST".equals(methodType))
                    ? new HttpPost(requestUri)
                    : new HttpPut(requestUri);

            if (request.getPostBodyLength() > 0) {
                enclosingMethod
                        .setEntity(new InputStreamEntity(request.getPostBody(), request.getPostBodyLength()));
            }
            httpMethod = enclosingMethod;
        } else if ("GET".equals(methodType)) {
            httpMethod = new HttpGet(requestUri);
        } else if ("HEAD".equals(methodType)) {
            httpMethod = new HttpHead(requestUri);
        } else if ("DELETE".equals(methodType)) {
            httpMethod = new HttpDelete(requestUri);
        }
        for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
            httpMethod.addHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
        }

        // Disable following redirects.
        if (!request.getFollowRedirects()) {
            httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        }

        // HttpClient doesn't handle all cases when breaking url (specifically '_' in domain)
        // So lets pass it the url parsed:
        response = FETCHER.execute(host, httpMethod);

        if (response == null) {
            throw new IOException("Unknown problem with request");
        }

        long now = System.currentTimeMillis();
        if (now - started > slowResponseWarning) {
            slowResponseWarning(request, started, now);
        }

        return makeResponse(response);

    } catch (Exception e) {
        long now = System.currentTimeMillis();

        // Find timeout exceptions, respond accordingly
        if (TIMEOUT_EXCEPTIONS.contains(e.getClass())) {
            LOG.info("Timeout for " + request.getUri() + " Exception: " + e.getClass().getName() + " - "
                    + e.getMessage() + " - " + (now - started) + "ms");
            return HttpResponse.timeout();
        }

        LOG.log(Level.INFO, "Got Exception fetching " + request.getUri() + " - " + (now - started) + "ms", e);

        // Separate shindig error from external error
        throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        // cleanup any outstanding resources..
        if (httpMethod != null)
            try {
                httpMethod.abort();
            } catch (UnsupportedOperationException e) {
                // ignore
            }
    }
}

From source file:net.tsz.afinal.http.HttpHandler.java

private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }//from w  w  w.j  a  v a2 s.c  o m
        if (fileLen > 0)
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
    }

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();//?
    while (retry) {
        try {
            if (isCancelled()) {
                return;
            }

            //POST:?;GET:?
            String requestUrl = request.getURI().toString();
            String requestMethod = request.getMethod();
            ZLogger.d(String.format("<%d><%s> %s", executionCount, requestMethod, requestUrl));

            for (Header header : request.getAllHeaders()) {
                ZLogger.d(String.format("<%s>:<%s>", header.getName(), header.getValue()));
            }

            //??url
            StringBuilder requestParams = new StringBuilder();
            if (requestMethod.equals(POST)) {
                HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) request;
                if (requestBase != null) {
                    HttpEntity entity = requestBase.getEntity();
                    if (entity != null) {
                        InputStream is = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        String line = null;
                        try {
                            while ((line = reader.readLine()) != null) {
                                //                            sb.append(line + "/n");
                                //                                Log.d("Nat: makeRequestWithRetries.request.Params.line", line);
                                requestParams.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            ZLogger.ef(e.toString());
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //                        byte[] paramsArray = EntityUtils.toByteArray(entity);
                    //                        String paramsStr = EntityUtils.toString(entity, "UTF-8");
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(2)", paramsStr);
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(3)", EntityUtils.toString(entity));
                }

                //                    Log.d("Nat: makeRequestWithRetries.request.Params(RAW)", requestParams.toString());
            }

            //
            HttpResponse response = client.execute(request, context);
            //                for(Header header : response.getAllHeaders()){
            //                    Log.d("Nat", String.format(" makeRequestWithRetries.respoonse.header <%s><%s>", header.getName(), header.getValue()));
            //                }

            if (isCancelled()) {
                ZLogger.d("Nat: makeRequestWithRetries", "request caneled.");
                return;
            }

            //POST:?;GET:?
            request.getRequestLine();//GET
            ZLogger.d(request.getRequestLine().toString());
            /*if (request.getMethod().equals("post")) {
            HttpParams params = request.getParams();
             params.setParameter(NetFactory.CLIENTSESSION, "");
            request.snetParams(params);
            }*/

            //?????()
            //executionCount < 1,?????
            if (response.containsHeader("needLogin")/* && executionCount < 1*/) {
                //?url?JSSIONID??cookie.
                //?(?),sessionId
                String newSid = MfhLoginService.get().doLogin();
                if (newSid == null) {
                    //TODO
                    //,?
                    //                        Intent intent = new Intent(Constants.ACTION_REDIRECT_TO_LOGIN_H5);
                    //                        BizApplication.getAppContext().sendBroadcast(intent);
                    //                        break;
                } else {
                    String cookie = String.format("%s=%s", FinalHttp.KEY_JSESSIONID, newSid);
                    request.addHeader(FinalHttp.HEADER_SET_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_cookie, cookie);
                    // ?
                    //                        MsgBridgeUtil.register();

                    if (requestMethod.equals(POST)) {
                        //                        //EntityJSSIONID
                        String newParams = replaceParam(requestParams.toString(), JSESSIONID, newSid);
                        //                            HttpEntity entity = new StringEntity(newParams);
                        HttpEntity entity = convertToAjaxParams(newParams).getEntity();
                        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
                    } else if (requestMethod.equals(GET)) {
                        //URLJSSIONID
                        String newRequestUrl = replaceParam(requestUrl, JSESSIONID, newSid);
                        //                            newRequestUrl = replaceParam(newRequestUrl, "lastupdate", "0");
                        URI uri = new URI(newRequestUrl);
                        //                            Log.d("Nat: makeRequestWithRetries.autoLogin.URI", uri.toString());
                        //                                HttpEntityEnclosingRequestBase requestFact = (HttpEntityEnclosingRequestBase)request;
                        //                                requestFact.setURI(uri);
                        ((HttpEntityEnclosingRequestBase) request).setURI(uri);
                    }
                }

                //TODO,?
                retry = (++executionCount <= MAX_RETRY_TIMES)
                        || retryHandler.retryRequest(new IOException("Exception"), executionCount, context);
                //                    ZLogger.d(String.format("%s  %d", retry ? "?" : "??", executionCount));
                if (retry) {
                    continue;
                }
            }

            //?
            handleResponse(response);
            return;
        } catch (UnknownHostException e) {
            ZLogger.e("UnknownHostException:" + e.toString());
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
            return;
        } catch (IOException e) {
            ZLogger.e("IOException: " + e.toString());
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (NullPointerException e) {
            if (e != null) {
                ZLogger.e("NullPointerException: " + e.toString());
                // here's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } else {
                ZLogger.e("NullPointerException: e is null");
            }
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (Exception e) {
            ZLogger.e("Exception: " + e.toString());
            cause = new IOException("Unhandled Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        }
    }

    // cleaned up to throw IOException
    if (cause != null) {
        throw cause;
    }
    //        else{
    //            //TODO
    //            throw new IOException("");
    //        }
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Executes an HTTP request and parses the RDF found in the response, returning it in a
 * {@link CloseableDataset}, then closes the response.
 *
 * @param client the client to use//from  w w w. ja  v  a2s . c  o  m
 * @param req the request to execute
 * @return the graph retrieved
 * @throws IOException in case of IOException
 */
private CloseableDataset getDataset(final CloseableHttpClient client, final HttpUriRequest req)
        throws IOException {
    if (!req.containsHeader(ACCEPT)) {
        req.addHeader(ACCEPT, "application/n-triples");
    }
    logger.debug("Retrieving RDF using mimeType: {}", req.getFirstHeader(ACCEPT));

    try (final CloseableHttpResponse response = client.execute(req)) {
        assertEquals(OK.getStatusCode(), response.getStatusLine().getStatusCode());
        final CloseableDataset result = parseTriples(response.getEntity());
        logger.trace("Retrieved RDF: {}", result);
        return result;
    }

}

From source file:org.geosdi.geoplatform.connector.server.request.json.GPBaseJsonConnectorRequest.java

/**
 * @return {@link T}//www. j  a v  a  2s.c  o  m
 * @throws Exception
 */
@Override
public T getResponse() throws Exception {
    HttpUriRequest httpMethod = this.prepareHttpMethod();
    httpMethod.addHeader("Content-Type", "application/json");
    logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString());
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode,
            this.getClass().getSimpleName());
    this.checkHttpResponseStatus(statusCode);
    HttpEntity responseEntity = httpResponse.getEntity();
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(responseEntity.getContent(), UTF_8_CHARSERT))) {
        return readInternal(reader);
    } catch (Exception ex) {
        throw new IncorrectResponseException(ex);
    } finally {
        consume(responseEntity);
        httpResponse.close();
    }
}

From source file:org.geosdi.geoplatform.connector.server.request.json.GPBaseJsonConnectorRequest.java

/**
 * <p>/*  w w w  .  ja  va 2  s  . c  o m*/
 * Method to generate Response AS a {@link String} value.
 * </p>
 *
 * @return {@link String}
 * @throws Exception
 */
@Override
public String getResponseAsString() throws Exception {
    HttpUriRequest httpMethod = this.prepareHttpMethod();
    httpMethod.addHeader("Content-Type", "application/json");
    logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString());
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode,
            this.getClass().getSimpleName());
    this.checkHttpResponseStatus(statusCode);
    HttpEntity responseEntity = httpResponse.getEntity();
    try {
        if (responseEntity != null) {
            return CharStreams.toString(new InputStreamReader(responseEntity.getContent(), UTF_8));
        } else {
            throw new IncorrectResponseException(CONNECTION_PROBLEM_MESSAGE);
        }
    } finally {
        consume(responseEntity);
        httpResponse.close();
    }
}

From source file:org.geosdi.geoplatform.connector.server.request.json.GPBaseJsonConnectorRequest.java

/**
 * <p>//from ww w  . java 2s . co  m
 * Method to generate Response AS a {@link InputStream} Stream. Remember to
 * close the Stream</p>
 *
 * @return {@link InputStream} stream
 * @throws Exception
 */
@Override
public InputStream getResponseAsStream() throws Exception {
    HttpUriRequest httpMethod = this.prepareHttpMethod();
    httpMethod.addHeader("Content-Type", "application/json");
    logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString());
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode,
            this.getClass().getSimpleName());
    this.checkHttpResponseStatus(statusCode);
    HttpEntity responseEntity = httpResponse.getEntity();
    try {
        if (responseEntity != null) {
            InputStream inputStream = responseEntity.getContent();
            return new ByteArrayInputStream(IOUtils.toByteArray(inputStream));
        } else {
            throw new IncorrectResponseException(CONNECTION_PROBLEM_MESSAGE);
        }
    } finally {
        consume(responseEntity);
        httpResponse.close();
    }
}

From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java

private Response sendRequest(OAuthCredentials credentials, BaseRequest request) {
    Validate.notNull(credentials);/*  w  ww .  j  a  v  a2 s  .  co  m*/
    String requestString = marshalRequest(request);

    URL apiUrlBase = apiUrl;

    // The client will use the API url if it's in the credentials
    if (StringUtils.isNotBlank(credentials.getApiUrl())) {
        try {
            apiUrlBase = new URL(credentials.getApiUrl());
        } catch (MalformedURLException e) {
            throw new FreshBooksException(e.getMessage());
        }
    }

    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.consumerKey, this.consumerSecret);
    consumer.setMessageSigner(new PlainTextMessageSigner());
    consumer.setTokenWithSecret(credentials.getAccessToken(), credentials.getAccessTokenSecret());
    consumer.setSigningStrategy(new AuthorizationHeaderSigningStrategy());

    logger.debug(String.format("Signing OAuth request [accessToken = %s] [accessTokenSecret = %s] ",
            consumer.getToken(), consumer.getTokenSecret()));
    logger.debug(String.format("API parameters [apiURL = %s]", apiUrlBase));

    Response response;
    HttpUriRequest uriRequest = new HttpPost(apiUrlBase.toString());
    try {
        ((HttpPost) uriRequest).setEntity(new StringEntity(requestString, "utf-8"));
        uriRequest.addHeader("Content-Type", "text/xml");

        consumer.sign(uriRequest);

        HttpResponse httpResponse = client.execute(uriRequest);
        InputStream is = httpResponse.getEntity().getContent();
        response = unmarshalResponse(is);
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new FreshBooksException(e);
    } finally {
        ((HttpPost) uriRequest).releaseConnection();
    }
    if (!"ok".equals(response.getStatus())) {
        throw new FreshBooksException(response.getError());
    }
    return response;
}