Example usage for org.apache.http.protocol HTTP USER_AGENT

List of usage examples for org.apache.http.protocol HTTP USER_AGENT

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP USER_AGENT.

Prototype

String USER_AGENT

To view the source code for org.apache.http.protocol HTTP USER_AGENT.

Click Source Link

Usage

From source file:com.phicomm.account.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*  ww  w .  j  a v a 2  s.c  o  m*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws ConnectionException {
    Thread.dumpStack();
    Log.i("ss", "NetworkConnectionImpl_____________________________________execute__urlValue:" + urlValue);
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (true) {
            Log.d(TAG, "Request url: " + urlValue);
            Log.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                Log.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    Log.d(TAG, message);
                }

                Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                Log.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                Log.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    Log.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            throw new ConnectionException(error, responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        if (true) {
            Log.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                Log.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*  w w w .j a va 2s.  com*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (DataDroidLog.canLog(Log.DEBUG)) {
            DataDroidLog.d(TAG, "Request url: " + urlValue);
            DataDroidLog.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                DataDroidLog.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    DataDroidLog.d(TAG, message);
                }

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                DataDroidLog.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                DataDroidLog.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            throw new ConnectionException(error, responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        if (DataDroidLog.canLog(Log.VERBOSE)) {
            DataDroidLog.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        DataDroidLog.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        DataDroidLog.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.sckftr.android.utils.net.Network.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from   w  w w . j av a2  s.  co m*/
 *
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param handler
 *@param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
*            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
*            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.        @return The result of the webservice call.
 */
static <Out> Out execute(Context context, String urlValue, Method method, Executor<BufferedReader, Out> handler,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws NetworkConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        //if (Log.canLog(Log.DEBUG)) {
        Log.d(TAG, method.toString() + ": " + urlValue);

        if (parameterList != null && !parameterList.isEmpty()) {
            //Log.d(TAG, "Parameters:");
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                Log.d(TAG, message);
            }

            //Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
        }

        if (postText != null) {
            Log.d(TAG, "Post data: " + postText);
        }

        if (headerMap != null && !headerMap.isEmpty()) {
            //Log.d(TAG, "Headers:");
            for (Entry<String, String> header : headerMap.entrySet()) {
                //Log.d(TAG, "- " + header.getKey() + " = " + header.getValue());
            }
        }
        //}

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new NetworkConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String err = evaluateStream(errorStream, new StringReaderHandler(), isGzip);
            throw new NetworkConnectionException(err, responseCode);
        }

        return evaluateStream(connection.getInputStream(), handler, isGzip);

    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new NetworkConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new NetworkConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new NetworkConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImplF.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from   www  .java  2 s  . c  om*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, File file) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (DataDroidLog.canLog(Log.DEBUG)) {
            DataDroidLog.d(TAG, "Request url: " + urlValue);
            DataDroidLog.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                DataDroidLog.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    DataDroidLog.d(TAG, message);
                }

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                DataDroidLog.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                DataDroidLog.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(READ_OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            throw new ConnectionException("error", responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip, file, context);

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        DataDroidLog.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        DataDroidLog.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.wso2.carbon.integrator.core.handler.IntegratorSynapseHandler.java

@Override
public boolean handleRequestInFlow(MessageContext messageContext) {
    boolean isPreserveHeadersContained = false;
    try {/*from w  ww.  j  a v a 2 s  .c  om*/
        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                .getAxis2MessageContext();
        Object isODataService = axis2MessageContext.getProperty("IsODataService");
        // In this if block we are skipping proxy services, inbound related message contexts & api.
        if (axis2MessageContext.getProperty("TransportInURL") != null && isODataService != null) {
            String uri = axis2MessageContext.getProperty("TransportInURL").toString();
            //OData web apps related logic
            WebApplication webApplication = Utils.getStartedWebapp(uri);
            if (webApplication != null) {
                String protocol = (String) messageContext.getProperty("TRANSPORT_IN_NAME");
                String host;
                Object headers = axis2MessageContext.getProperty("TRANSPORT_HEADERS");
                if (headers instanceof TreeMap) {
                    host = Utils.getHostname((String) ((TreeMap) headers).get("Host"));
                    isPreserveHeadersContained = true;
                    String endpoint = protocol + "://" + host + ":" + Utils.getProtocolPort(protocol);
                    return dispatchMessage(endpoint, uri, messageContext);
                }
            }
        }
        return true;
    } catch (Exception e) {
        this.handleException("Error occurred in integrator handler.", e, messageContext);
        return true;
    } finally {
        if (isPreserveHeadersContained) {
            if (passThroughSenderManager != null
                    && passThroughSenderManager.getSharedPassThroughHttpSender() != null) {
                try {
                    passThroughSenderManager.getSharedPassThroughHttpSender()
                            .removePreserveHttpHeader(HTTP.USER_AGENT);
                    // This catch is added when there is no preserve headers in the PassthoughHttpSender.
                } catch (ArrayIndexOutOfBoundsException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("ArrayIndexOutOfBoundsException exception occurred, when removing preserve "
                                + "headers.");
                    }
                }
            }
        }
    }
}

From source file:com.gallery.GalleryRemote.GalleryComm.java

protected GalleryComm(Gallery g, StatusUpdate su) {
    if (g == null) {
        throw new IllegalArgumentException("Must supply a non-null gallery.");
    }/*from w w  w.  ja v a2s .c o  m*/

    this.g = g;
    this.su = su;

    SingleClientConnManager cm = null;

    // Set all-trusting SSL manager, if necessary
    if (g.getUrl().getProtocol().equals("https")) {
        try {
            SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"),
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", sf, 443));
            cm = new SingleClientConnManager(schemeRegistry);
        } catch (NoSuchAlgorithmException e) {
            Log.logException(Log.LEVEL_CRITICAL, MODULE, e);
        }
    }

    httpclient = new DefaultHttpClient(cm);

    // Use default proxy (as defined by the JVM)
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpclient.setRoutePlanner(routePlanner);

    // use GR User-Agent
    httpclient.removeRequestInterceptorByClass(RequestUserAgent.class);
    final String ua = g.getUserAgent();
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            request.setHeader(HTTP.USER_AGENT, ua);
        }
    });
}

From source file:org.yamj.api.common.http.DefaultPoolingHttpClient.java

@Override
public HttpEntity requestResource(HttpGet httpGet) throws IOException {
    if (randomUserAgent) {
        httpGet.setHeader(HTTP.USER_AGENT, UserAgentSelector.randomUserAgent());
    }/*from w w w.ja v a2  s.c o m*/
    HttpResponse response = execute(httpGet);
    return response.getEntity();
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {//  w  w  w . j a v  a 2 s . com
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(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.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // 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());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

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

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.omertron.rottentomatoesapi.tools.ResponseBuilder.java

/**
 * Get the content from a string, decoding it if it is in GZIP format
 *
 * @param urlString/*from w  w w  . j a v a2s.c o  m*/
 * @return
 * @throws RottenTomatoesException
 */
private String getContent(String url) throws RottenTomatoesException {
    LOG.trace("Requesting: {}", url);
    try {
        final HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("accept", "application/json");
        httpGet.addHeader(HTTP.USER_AGENT, UserAgentSelector.randomUserAgent());

        final DigestedResponse response = DigestedResponseReader.requestContent(httpClient, httpGet, charset);

        if (response.getStatusCode() >= HTTP_STATUS_500) {
            throw new RottenTomatoesException(ApiExceptionType.HTTP_503_ERROR, response.getContent(),
                    response.getStatusCode(), url);
        } else if (response.getStatusCode() >= HTTP_STATUS_300) {
            throw new RottenTomatoesException(ApiExceptionType.HTTP_404_ERROR, response.getContent(),
                    response.getStatusCode(), url);
        }

        return response.getContent();
    } catch (IOException ex) {
        throw new RottenTomatoesException(ApiExceptionType.CONNECTION_ERROR, "Error retrieving URL", url, ex);
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.RemoteStorageContextCustomizer.java

@Override
public void customize(final Builder builder) {
    // connection/socket timeouts
    int timeout = 1000;
    if (context.getRemoteConnectionSettings() != null) {
        timeout = context.getRemoteConnectionSettings().getConnectionTimeout();
    }// w w  w  .  j a  v  a2  s .c  o m
    builder.getSocketConfigBuilder().setSoTimeout(timeout);
    builder.getRequestConfigBuilder().setConnectTimeout(timeout);
    builder.getRequestConfigBuilder().setSocketTimeout(timeout);

    // obey the given retries count and apply it to client.
    int retries = context.getRemoteConnectionSettings() != null
            ? context.getRemoteConnectionSettings().getRetrievalRetryCount()
            : 0;
    builder.getHttpClientBuilder().setRetryHandler(new StandardHttpRequestRetryHandler(retries, false));

    applyAuthenticationConfig(builder, context.getRemoteAuthenticationSettings(), null);
    applyProxyConfig(builder, context.getRemoteProxySettings());

    // Apply optional context-specific user-agent suffix
    if (context.getRemoteConnectionSettings() != null) {
        String userAgentSuffix = context.getRemoteConnectionSettings().getUserAgentCustomizationString();
        if (!StringUtils.isEmpty(userAgentSuffix)) {
            final String customizedUserAgent = builder.getUserAgent() + " " + userAgentSuffix;
            builder.setUserAgent(customizedUserAgent);
            builder.getHttpClientBuilder().setRequestExecutor(new HttpRequestExecutor() {
                @Override
                public void preProcess(final HttpRequest request, final HttpProcessor processor,
                        final HttpContext ctx) throws HttpException, IOException {
                    // NEXUS-7575: In case of HTTP Proxy tunnel, add generic UA while performing CONNECT
                    if (!request.containsHeader(HTTP.USER_AGENT)) {
                        request.addHeader(new BasicHeader(HTTP.USER_AGENT, customizedUserAgent));
                    }
                    super.preProcess(request, processor, ctx);
                }
            });
        }
    }
}