Example usage for org.apache.http.auth AuthScope ANY_HOST

List of usage examples for org.apache.http.auth AuthScope ANY_HOST

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY_HOST.

Prototype

String ANY_HOST

To view the source code for org.apache.http.auth AuthScope ANY_HOST.

Click Source Link

Document

The null value represents any host.

Usage

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean patch2DjangoJSONArray(Context context, JSONArray jsonArray, String uploadurl,
        String username, String password) {

    String response = "";

    try {//from   w ww  .  j  a v a  2s .c o m

        JSONObject obj = new JSONObject();
        obj.put("objects", jsonArray);
        JSONArray emptyarray = new JSONArray();
        obj.put("deleted_objects", emptyarray);

        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        // Create a new HttpClient and Post Header
        HttpPatch httppatch = new HttpPatch(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppatch.setHeader("Content-type", "application/json");

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.setCredentialsProvider(credProvider);
        // ByteArrayEntity bae = new ByteArrayEntity(obj.toString()
        // .getBytes("UTF8"));

        StringEntity se = new StringEntity(obj.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        // bae.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
        // "application/json"));
        httppatch.setEntity(se);

        // Execute HTTP Post Request

        HttpResponse httpResponse = httpclient.execute(httppatch);

        response = httpResponse.getStatusLine().toString();

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (response.contains("ACCEPTED")) {
        return true;
    } else {
        return false;
    }

}

From source file:nl.nn.adapterframework.http.HttpSenderBase.java

public void configure() throws ConfigurationException {
    super.configure();

    if (!getMethodType().equals("POST")) {
        if (!isParamsInUrl()) {
            throw new ConfigurationException(
                    getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
        }//from   ww  w .  jav  a 2  s . c  o m
        if (StringUtils.isNotEmpty(getInputMessageParam())) {
            throw new ConfigurationException(
                    getLogPrefix() + "inputMessageParam can only be set for methodType POST");
        }
    }

    /**
     * TODO find out if this really breaks proxy authentication or not.
     */
    //      httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(getTimeout());
    requestConfig.setConnectionRequestTimeout(getTimeout());
    requestConfig.setSocketTimeout(getTimeout());

    if (paramList != null) {
        paramList.configure();
        if (StringUtils.isNotEmpty(getUrlParam())) {
            urlParameter = paramList.findParameter(getUrlParam());
            addParameterToSkip(urlParameter);
        }
    }
    if (getMaxConnections() <= 0) {
        throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections()
                + "], which is not enough for adequate operation");
    }
    try {
        if (urlParameter == null) {
            if (StringUtils.isEmpty(getUrl())) {
                throw new ConfigurationException(
                        getLogPrefix() + "url must be specified, either as attribute, or as parameter");
            }
            staticUri = getURI(getUrl());
        }

        URL certificateUrl = null;
        URL truststoreUrl = null;

        if (!StringUtils.isEmpty(getCertificate())) {
            certificateUrl = ClassUtils.getResourceURL(getClassLoader(), getCertificate());
            if (certificateUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
            }
            log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
        }
        if (!StringUtils.isEmpty(getTruststore())) {
            truststoreUrl = ClassUtils.getResourceURL(getClassLoader(), getTruststore());
            if (truststoreUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
            }
            log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
        }

        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        if (!isVerifyHostname())
            hostnameVerifier = new NoopHostnameVerifier();

        // Add javax.net.ssl.SSLSocketFactory.getDefault() SSLSocketFactory if non has been set.
        // See: http://httpcomponents.10934.n7.nabble.com/Upgrading-commons-httpclient-3-x-to-HttpClient4-x-td19333.html
        // 
        // The first time this method is called, the security property "ssl.SocketFactory.provider" is examined. 
        // If it is non-null, a class by that name is loaded and instantiated. If that is successful and the 
        // object is an instance of SSLSocketFactory, it is made the default SSL socket factory.
        // Otherwise, this method returns SSLContext.getDefault().getSocketFactory(). If that call fails, an inoperative factory is returned.
        javax.net.ssl.SSLSocketFactory socketfactory = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory
                .getDefault();
        sslSocketFactory = new SSLConnectionSocketFactory(socketfactory, hostnameVerifier);

        if (certificateUrl != null || truststoreUrl != null || isAllowSelfSignedCertificates()) {
            try {
                CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null,
                        getCertificatePassword());
                CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null,
                        getTruststorePassword());

                SSLContext sslContext = AuthSSLConnectionSocket.createSSLContext(certificateUrl,
                        certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl,
                        truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(),
                        isAllowSelfSignedCertificates(), isVerifyHostname(),
                        isIgnoreCertificateExpiredException(), getProtocol());

                sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
                log.debug(getLogPrefix() + "created custom SSLConnectionSocketFactory");

            } catch (Throwable t) {
                throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory",
                        t);
            }
        }

        // This method will be overwritten by the connectionManager when connectionPooling is enabled!
        // Can still be null when no default or an invalid system sslSocketFactory has been defined
        if (sslSocketFactory != null)
            httpClientBuilder.setSSLSocketFactory(sslSocketFactory);

        credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(credentials.getUsername())) {
            String uname;
            if (StringUtils.isNotEmpty(getAuthDomain())) {
                uname = getAuthDomain() + "\\" + credentials.getUsername();
            } else {
                uname = credentials.getUsername();
            }

            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(uname, credentials.getPassword()));

            requestConfig.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            requestConfig.setAuthenticationEnabled(true);
        }
        if (StringUtils.isNotEmpty(getProxyHost())) {
            HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
            AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);

            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(),
                    getProxyPassword());

            if (StringUtils.isNotEmpty(pcf.getUsername())) {
                Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
                credentialsProvider.setCredentials(scope, credentials);
            }
            log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");

            if (prefillProxyAuthCache()) {
                requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));

                AuthCache authCache = httpClientContext.getAuthCache();
                if (authCache == null)
                    authCache = new BasicAuthCache();

                authCache.put(proxy, new BasicScheme());
                httpClientContext.setAuthCache(authCache);
            }

            requestConfig.setProxy(proxy);
            httpClientBuilder.setProxy(proxy);
        }

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
    }

    if (StringUtils.isNotEmpty(getStyleSheetName())) {
        try {
            URL stylesheetURL = ClassUtils.getResourceURL(getClassLoader(), getStyleSheetName());
            if (stylesheetURL == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
            }
            transformerPool = TransformerPool.getInstance(stylesheetURL);
        } catch (IOException e) {
            throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]",
                    e);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException(
                    getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]",
                    te);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

    // The redirect strategy used to only redirect GET, DELETE and HEAD.
    httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return isFollowRedirects();
        }
    });
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

protected void setAuthenticationInfo(AbstractHttpClient agent, MessageContext msgCtx) throws AxisFault {
    HTTPAuthenticator authenticator;//ww w . j  a  va 2 s .  co  m
    Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE);
    if (obj != null) {
        if (obj instanceof HTTPAuthenticator) {
            authenticator = (HTTPAuthenticator) obj;

            String username = authenticator.getUsername();
            String password = authenticator.getPassword();
            String host = authenticator.getHost();
            String domain = authenticator.getDomain();

            int port = authenticator.getPort();
            String realm = authenticator.getRealm();

            /* If retrying is available set it first */
            isAllowedRetry = authenticator.isAllowedRetry();

            Credentials creds;

            // TODO : Set preemptive authentication, but its not recommended in HC 4

            if (host != null) {
                if (domain != null) {
                    /* Credentials for NTLM Authentication */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, host, domain);
                } else {
                    /* Credentials for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                }
                agent.getCredentialsProvider().setCredentials(new AuthScope(host, port, realm), creds);
            } else {
                if (domain != null) {
                    /*
                     * Credentials for NTLM Authentication when host is
                     * ANY_HOST
                     */
                    agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain);
                    agent.getCredentialsProvider()
                            .setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds);
                } else {
                    /* Credentials only for Digest and Basic Authentication */
                    creds = new UsernamePasswordCredentials(username, password);
                    agent.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), creds);
                }
            }
            /* Customizing the priority Order */
            List schemes = authenticator.getAuthSchemes();
            if (schemes != null && schemes.size() > 0) {
                List authPrefs = new ArrayList(3);
                for (int i = 0; i < schemes.size(); i++) {
                    if (schemes.get(i) instanceof AuthPolicy) {
                        authPrefs.add(schemes.get(i));
                        continue;
                    }
                    String scheme = (String) schemes.get(i);
                    authPrefs.add(authenticator.getAuthPolicyPref(scheme));

                }
                agent.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPrefs);
            }

        } else {
            throw new AxisFault("HttpTransportProperties.Authenticator class cast exception");
        }
    }

}

From source file:com.rabbitmq.http.client.Client.java

private CredentialsProvider getCredentialsProvider(final URL url, final String username,
        final String password) {
    CredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    return cp;//from  ww w .j a v  a  2s.c om
}

From source file:net.tac42.subtails.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;// w ww  . jav a  2s  . c o  m
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

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

        // Set credentials to get through apache proxies that require authentication.
        SharedPreferences prefs = Util.getPreferences(context);
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:github.madmarty.madsonic.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);/*  w  w w  .j  av a 2  s. c  o  m*/

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

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

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    LOG.info("Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;// ww w. j a  v  a2  s .  c  om
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            LOG.debug("Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

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

        // Set credentials to get through apache proxies that require authentication.
        ServerSettingsManager.ServerSettings server = Util.getActiveServer(context);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(server.getUsername(), server.getPassword()));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            LOG.warn("Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:org.webservice.fotolia.FotoliaApi.java

/**
 * Construct and returns a usuable http client
 *
 * @param  auto_refresh_token//from  w  w w.j  a  v a2  s.co  m
 * @return DefaultHttpClient
 */
private DefaultHttpClient _getHttpClient(final boolean auto_refresh_token) {
    DefaultHttpClient client;

    client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(this._api_key, this._getSessionId(auto_refresh_token)));

    HttpConnectionParams.setConnectionTimeout(client.getParams(), FotoliaApi.API_CONNECT_TIMEOUT * 1000);
    HttpConnectionParams.setSoTimeout(client.getParams(), FotoliaApi.API_PROCESS_TIMEOUT * 1000);

    return client;
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    // Strip out sensitive information from log
    Log.i(TAG, "Using URL " + url.substring(0, url.indexOf("?u=") + 1) + url.substring(url.indexOf("&v=") + 1));

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);//from  w ww  . j  a  va 2s  .c o  m

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                cancelled.set(true);
                                request.abort();
                            } catch (Exception e) {
                                Log.e(TAG, "Failed to stop http task");
                            }
                        }
                    }).start();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

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

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}