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

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

Introduction

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

Prototype

public void addHeader(String str, String str2) 

Source Link

Usage

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeHeaders(final HttpRequestBase httpRequest, HttpClientRequest<T> httpClientRequest) {
    final String virtualHost = httpClientRequest.getVirtualHost();
    final List<HttpClientHeader> headers = httpClientRequest.getHeaders();
    if (CollectionUtils.isNotEmpty(headers)) {
        for (final HttpClientHeader httpHeader : headers) {
            final String headerName = httpHeader.getName();

            // Don't add Host headers, let the virtual host setting do its trick.
            if (virtualHost == null || !"host".equals(headerName.toLowerCase(Locale.ENGLISH))) {

                LOG.debug("Adding Header '%s' : '%s' to the request", headerName, httpHeader.getValue());

                httpRequest.addHeader(headerName, httpHeader.getValue());
            }//from   w  w  w .j ava  2 s . c  om
        }
    }
}

From source file:com.google.wireless.speed.speedometer.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override/*from www.ja  v a  2 s  .c om*/
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Log.i(SpeedometerApp.TAG, MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(SpeedometerApp.TAG, "Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public String invoke(@Nonnull String method, @Nonnull String account, @Nonnull String resource,
        @Nonnull String body) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }/*from   www  .  ja  v  a  2  s.  c o m*/
    if (wire.isDebugEnabled()) {
        wire.debug("POST --------------------------------------------------------> " + endpoint + account
                + resource);
        wire.debug("");
    }
    String requestId = null;
    try {
        HttpClient client = getClient();
        String url = endpoint + account + resource;

        HttpRequestBase httpMethod = getMethod(method, url);

        //If it is networking configuration services
        if (httpMethod instanceof HttpPut) {
            if (url.endsWith("/services/networking/media")) {
                httpMethod.addHeader("Content-Type", "text/plain");
            } else {
                httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
            }
        } else {
            httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
        }

        //dmayne version is older for anything to do with images and for disk deletion
        if (url.indexOf("/services/images") > -1
                || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
            httpMethod.addHeader("x-ms-version", "2012-08-01");
        } else {
            httpMethod.addHeader("x-ms-version", "2012-03-01");
        }
        if (wire.isDebugEnabled()) {
            wire.debug(httpMethod.getRequestLine().toString());
            for (Header header : httpMethod.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                wire.debug(body);
                wire.debug("");
            }
        }

        if (httpMethod instanceof HttpEntityEnclosingRequestBase) {

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod;

            if (body != null) {
                try {
                    entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new CloudException(e);
                }
            }
        }

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(httpMethod);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                    if (h.getName().equalsIgnoreCase("x-ms-request-id")) {
                        requestId = h.getValue().trim();
                    }
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT) {
            logger.warn("Expected OK, got " + status.getStatusCode());

            String responseBody = "";

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                responseBody = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            logger.debug(responseBody);
            logger.debug("https: char " + responseBody.indexOf("https://"));
            logger.debug("account number: char " + responseBody.indexOf(account));
            String tempEndpoint = responseBody.substring(responseBody.indexOf("https://"),
                    responseBody.indexOf(account) - responseBody.indexOf("https://"));
            logger.debug("temp redirect location: " + tempEndpoint);
            tempRedirectInvoke(tempEndpoint, method, account, resource, body);
        } else if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
            }
            logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("POST --------------------------------------------------------> " + endpoint + account
                    + resource);
        }
    }
    return requestId;
}

From source file:com.mobiperf.speedometer.measurements.HttpTask.java

/**
 * Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off
 *//* w  w w.j a v  a  2  s  .c o m*/
@Override
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    //ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /*
         * TODO(Wenjie): HttpClient does not automatically handle the following codes 301 Moved
         * Permanently. HttpStatus.SC_MOVED_PERMANENTLY 302 Moved Temporarily.
         * HttpStatus.SC_MOVED_TEMPORARILY 303 See Other. HttpStatus.SC_SEE_OTHER 307 Temporary
         * Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page.
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
            Logger.i(">>> success = " + success + " " + statusCode);
        } else {
            Logger.i(">>> statusLine is null");
        }

        /*
         * For HttpClient to work properly, we still want to consume the entire response even if the
         * status code is not 200
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is
        // unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                //          if (body.remaining() > 0) {
                //            int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                //            body.put(readBuffer, 0, putLen);
                //          }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in each header field. I
                 * cannot find internal methods that return the number of bytes in a header. The solution
                 * here assumes the encoding is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            //result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

protected void authorize(@Nonnull ProviderContext ctx, @Nonnull HttpRequestBase method,
        @Nonnull String contentType, @Nullable String range) throws CloudException, InternalException {
    ArrayList<Header> emcHeaders = new ArrayList<Header>();
    String date = provider.formatTime(System.currentTimeMillis());

    try {//w  ww. j av  a 2  s  .  c o  m
        method.addHeader("x-emc-uid",
                new String(ctx.getAccessPublic(), "utf-8") + "/" + ctx.getAccountNumber());
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 error: " + e.getMessage());
        throw new InternalException(e);
    }
    method.addHeader("Date", date);

    for (Header h : method.getAllHeaders()) {
        if (h.getName().toLowerCase().startsWith("x-emc")) {
            emcHeaders.add(h);
        }
    }
    String signatureString = toSignatureString(method, contentType, range == null ? "" : range, date,
            method.getURI(), emcHeaders);
    logger.debug(signatureString);
    String signature = sign(ctx, signatureString);
    logger.debug(signature);
    method.addHeader("x-emc-signature", signature);
}

From source file:com.mobiperf.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override/* w ww . ja v  a 2 s  .com*/
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    // This is not the ideal way of doing things, as we can pick up data
    // from other processes and be overly cautious in running measurements.
    // However, taking the packet sizes is completely inaccurate, and it's hard to
    // come up with a consistent expected value, unlike with DNS
    RRCTask.PacketMonitor packetmonitor = new RRCTask.PacketMonitor();
    packetmonitor.setBySize();
    packetmonitor.readCurrentPacketValues();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed = packetmonitor.getPacketsSentDiff();

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.mobiperf_library.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *///from  w ww. ja  v  a2 s  . co  m
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.triarc.sync.SyncAdapter.java

private HttpRequestBase createRequest(SyncTypeCollection typeCollection, String password, String path,
        MutableBoolean hasChanges) throws Exception, IOException, UnsupportedEncodingException {
    String localTableName = typeCollection.getName();
    Log.i(TAG, "Streaming data for type: " + localTableName);

    String actionPath = path + "/" + typeCollection.getController() + "/" + typeCollection.getAction();

    HttpRequestBase request;

    HttpPost httppost = new HttpPost(actionPath);
    request = httppost;/*from www . j  a  v  a2 s  .  c  o  m*/

    JSONObject entity;

    try {
        entity = this.getVersionSets(typeCollection, hasChanges);
    } finally {
        if (hasChanges.getValue()) {
            // keep the ui locked until the change is confirmed from the
            // server
            hasChanges.setValue(true);
            this.lockUi(typeCollection);
        }
    }

    httppost.setEntity(new StringEntity(entity.toString(), HTTP.UTF_8));

    request.setHeader("Content-Type", "application/json; charset=utf-8");

    request.addHeader("Cookie", password);
    return request;
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        final Output writer, final BindingSession session, BigInteger offset, BigInteger length) {
    int respCode = -1;

    try {//w  w  w  . j  a v a2  s.co m
        // log before connect
        if (LOG.isDebugEnabled()) {
            LOG.debug("Session {}: {} {}", session.getSessionId(), method, url);
        }

        // get HTTP client object from session
        DefaultHttpClient httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT);
        if (httpclient == null) {
            session.writeLock();
            try {
                httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT);
                if (httpclient == null) {
                    httpclient = createHttpClient(url, session);
                    session.put(HTTP_CLIENT, httpclient, true);
                }
            } finally {
                session.writeUnlock();
            }
        }

        HttpRequestBase request = null;

        if ("GET".equals(method)) {
            request = new HttpGet(url.toString());
        } else if ("POST".equals(method)) {
            request = new HttpPost(url.toString());
        } else if ("PUT".equals(method)) {
            request = new HttpPut(url.toString());
        } else if ("DELETE".equals(method)) {
            request = new HttpDelete(url.toString());
        } else {
            throw new CmisRuntimeException("Invalid HTTP method!");
        }

        // set content type
        if (contentType != null) {
            request.setHeader("Content-Type", contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getKey() != null && isNotEmpty(header.getValue())) {
                        String key = header.getKey();
                        if (key.equalsIgnoreCase("user-agent")) {
                            request.setHeader("User-Agent", header.getValue().get(0));
                        } else {
                            for (String value : header.getValue()) {
                                if (value != null) {
                                    request.addHeader(key, value);
                                }
                            }
                        }
                    }
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append('-');

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            request.setHeader("Range", sb.toString());
        }

        // compression
        Object compression = session.get(SessionParameter.COMPRESSION);
        if ((compression != null) && Boolean.parseBoolean(compression.toString())) {
            request.setHeader("Accept-Encoding", "gzip,deflate");
        }

        // locale
        if (session.get(CmisBindingsHelper.ACCEPT_LANGUAGE) instanceof String) {
            request.setHeader("Accept-Language", session.get(CmisBindingsHelper.ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            final boolean clientCompressionFlag = (clientCompression != null)
                    && Boolean.parseBoolean(clientCompression.toString());
            if (clientCompressionFlag) {
                request.setHeader("Content-Encoding", "gzip");
            }

            AbstractHttpEntity streamEntity = new AbstractHttpEntity() {
                @Override
                public boolean isChunked() {
                    return true;
                }

                @Override
                public boolean isRepeatable() {
                    return false;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }

                @Override
                public boolean isStreaming() {
                    return false;
                }

                @Override
                public InputStream getContent() throws IOException {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStream connOut = null;

                    if (clientCompressionFlag) {
                        connOut = new GZIPOutputStream(outstream, 4096);
                    } else {
                        connOut = outstream;
                    }

                    OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
                    try {
                        writer.write(out);
                    } catch (IOException ioe) {
                        throw ioe;
                    } catch (Exception e) {
                        throw new IOException(e);
                    }
                    out.flush();

                    if (connOut instanceof GZIPOutputStream) {
                        ((GZIPOutputStream) connOut).finish();
                    }
                }
            };
            ((HttpEntityEnclosingRequestBase) request).setEntity(streamEntity);
        }

        // connect
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        // get stream, if present
        respCode = response.getStatusLine().getStatusCode();
        InputStream inputStream = null;
        InputStream errorStream = null;

        if ((respCode == 200) || (respCode == 201) || (respCode == 203) || (respCode == 206)) {
            if (entity != null) {
                inputStream = entity.getContent();
            } else {
                inputStream = new ByteArrayInputStream(new byte[0]);
            }
        } else {
            if (entity != null) {
                errorStream = entity.getContent();
            } else {
                errorStream = new ByteArrayInputStream(new byte[0]);
            }
        }

        // collect headers
        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : response.getAllHeaders()) {
            List<String> values = responseHeaders.get(header.getName());
            if (values == null) {
                values = new ArrayList<String>();
                responseHeaders.put(header.getName(), values);
            }
            values.add(header.getValue());
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace("Session {}: {} {} > Headers: {}", session.getSessionId(), method, url,
                    responseHeaders.toString());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, responseHeaders);
        }

        // get the response
        return new Response(respCode, response.getStatusLine().getReasonPhrase(), responseHeaders, inputStream,
                errorStream);
    } catch (Exception e) {
        String status = (respCode > 0 ? " (HTTP status code " + respCode + ")" : "");
        throw new CmisConnectionException("Cannot access \"" + url + "\"" + status + ": " + e.getMessage(), e);
    }
}

From source file:org.dasein.cloud.aws.storage.GlacierMethod.java

private ClientAndResponse invokeInternal() throws InternalException, CloudException {

    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug("----------------------------------------------------------------------------------");
    }// w w  w . j a v a2  s  . c  o m
    try {
        final String url = getUrlWithParameters();
        final String host;
        try {
            host = new URI(url).getHost();
        } catch (URISyntaxException e) {
            throw new InternalException(e);
        }
        final HttpRequestBase method = action.getMethod(url);

        final HttpClient client = provider.getClient();

        final String accessId;
        final String secret;
        try {
            accessId = new String(provider.getContext().getAccessPublic(), "utf-8");
            secret = new String(provider.getContext().getAccessPrivate(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        headers.put(AWSCloud.P_AWS_DATE, provider.getV4HeaderDate(null));
        headers.put("x-amz-glacier-version", API_VERSION);
        headers.put("host", host);
        final String v4Authorization = provider.getV4Authorization(accessId, secret, method.getMethod(), url,
                SERVICE_ID, headers, getRequestBodyHash());
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
        method.addHeader(AWSCloud.P_CFAUTH, v4Authorization);

        if (bodyText != null) {
            try {
                ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(bodyText));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
        }

        if (wire.isDebugEnabled()) {
            wire.debug("[" + url + "]");
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (bodyText != null) {
                try {
                    wire.debug(EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
        }

        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(method);
        } catch (IOException e) {
            throw new CloudException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(httpResponse.getStatusLine().toString());
            for (Header header : httpResponse.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }

        int status = httpResponse.getStatusLine().getStatusCode();
        if (status >= 400) {
            throw getGlacierException(httpResponse);
        } else {
            return new ClientAndResponse(client, httpResponse);
        }
    } finally {
        if (wire.isDebugEnabled()) {
            wire.debug("----------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}