Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getParams.

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:com.box.androidlib.BoxFileUpload.java

/**
 * Execute a file upload.//from  w ww .ja  va  2 s  . co m
 * 
 * @param action
 *            Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}
 * @param sourceInputStream
 *            Input stream targeting the data for the file you wish to create/upload to Box.
 * @param filename
 *            The desired filename on Box after upload (just the file name, do not include the path)
 * @param destinationId
 *            If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that
 *            is being overwritten, or copied.
 * @return A FileResponseParser with information about the upload.
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 * @throws FileNotFoundException
 *             File being uploaded either doesn't exist, is not a file, or cannot be read
 * @throws MalformedURLException
 *             Make sure you have specified a valid upload action
 */
public FileResponseParser execute(final String action, final InputStream sourceInputStream,
        final String filename, final long destinationId)
        throws IOException, MalformedURLException, FileNotFoundException {

    if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE)
            && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        throw new MalformedURLException("action must be upload, overwrite or new_copy");
    }

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getUploadUrlScheme());
    builder.encodedAuthority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    if (action.equals(Box.UPLOAD_ACTION_OVERWRITE)) {
        builder.appendQueryParameter("file_name", filename);
    } else if (action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        builder.appendQueryParameter("new_file_name", filename);
    }

    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
    }

    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //            DevUtils.logcat("Uploading : " + filename + "  Action= " + action + " DestinionID + " + destinationId);
        DevUtils.logcat("Upload URL : " + builder.build().toString());
    }
    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8));

    if (mListener != null && mHandler != null) {
        reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() {

            @Override
            public void onTransferred(final long bytesTransferredCumulative) {
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListener.onProgress(bytesTransferredCumulative);
                    }
                });
            }
        });
    }

    reqEntity.addPart("file_name", new InputStreamBody(sourceInputStream, filename) {

        @Override
        public String getFilename() {
            return filename;
        }
    });
    post.setEntity(reqEntity);

    // Send request
    final HttpResponse httpResponse;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpClient.getParams(), BoxConfig.getInstance().getUserAgent());
    post.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
    try {
        httpResponse = httpClient.execute(post);
    } catch (final IOException e) {
        // Detect if the download was cancelled through thread interrupt. See CountingOutputStream.write() for when this exception is thrown.
        if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
            //                DevUtils.logcat("IOException Uploading " + filename + " Exception Message: " + e.getMessage() + e.toString());
            DevUtils.logcat(" Exception : " + e.toString());
            e.printStackTrace();
            DevUtils.logcat("Upload URL : " + builder.build().toString());
        }
        if ((e.getMessage() != null && e.getMessage().equals(FileUploadListener.STATUS_CANCELLED))
                || Thread.currentThread().isInterrupted()) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            httpClient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);
        }
    }
    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        DevUtils.logcat("HTTP Response Code: " + httpResponse.getStatusLine().getStatusCode());
        Header[] headers = httpResponse.getAllHeaders();
        //            DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpClient.getParams()));
        //            for (Header header : headers) {
        //                DevUtils.logcat("Response Header: " + header.toString());
        //            }
    }

    // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
        final FileResponseParser handler = new FileResponseParser();
        handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
        return handler;
    }

    String status = null;
    BoxFile boxFile = null;
    final InputStream is = httpResponse.getEntity().getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    httpResponse.getEntity().consumeContent();
    final String xml = sb.toString();

    try {
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));
        final Node statusNode = doc.getElementsByTagName("status").item(0);
        if (statusNode != null) {
            status = statusNode.getFirstChild().getNodeValue();
        }
        final Element fileEl = (Element) doc.getElementsByTagName("file").item(0);
        if (fileEl != null) {
            try {
                boxFile = Box.getBoxFileClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fileEl.getAttributes().getLength(); i++) {
                boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(),
                        fileEl.getAttributes().item(i).getNodeValue());
            }
        }

        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        if (status == null) {
            status = xml;
        }
    } catch (final SAXException e) {
        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        status = xml;
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    }
    final FileResponseParser handler = new FileResponseParser();
    handler.setFile(boxFile);
    handler.setStatus(status);
    return handler;
}

From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java

@Override
public void run() {
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
        return;//w  ww  .  j  a v  a 2 s .co m
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials());
    if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) {
        try {
            URL url = new URL(config.getGerritProxy());
            HttpHost proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
            if (altLogger != null) {
                altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage());
            }
        }
    }
    try {
        HttpResponse httpResponse = httpclient.execute(httpPost);
        String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase());
            if (altLogger != null) {
                altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase());
            }
        }
    } catch (Exception e) {
        logger.error("Failed to submit result to Gerrit", e);
        if (altLogger != null) {
            altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString());
        }
    }
}

From source file:org.xmlsh.internal.commands.http.java

private void setOptions(DefaultHttpClient client, HttpHost host, Options opts)
        throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException,
        CertificateException, FileNotFoundException, KeyStoreException, IOException {

    HttpParams params = client.getParams();
    HttpConnectionParamBean connection = new HttpConnectionParamBean(params);

    if (opts.hasOpt("connectTimeout"))
        connection.setConnectionTimeout((int) (opts.getOptDouble("connectTimeout", 0) * 1000.));

    if (opts.hasOpt("readTimeout"))
        connection.setSoTimeout((int) (opts.getOptDouble("readTimeout", 0) * 1000.));

    /*/*from   ww w .j a va 2s  .c  o  m*/
     * if( opts.hasOpt("useCaches"))
     * client.setUseCaches( opts.getOpt("useCaches").getFlag());
     * 
     * 
     * if( opts.hasOpt("followRedirects"))
     * 
     * client.setInstanceFollowRedirects(
     * opts.getOpt("followRedirects").getFlag());
     * 
     * 
     * 
     * 
     * 
     * 
     * String disableTrustProto = opts.getOptString("disableTrust", null);
     * 
     * String keyStore = opts.getOptString("keystore", null);
     * String keyPass = opts.getOptString("keypass", null);
     * String sslProto = opts.getOptString("sslProto", "SSLv3");
     * 
     * if(disableTrustProto != null && client instanceof HttpsURLConnection )
     * disableTrust( (HttpsURLConnection) client , disableTrustProto );
     * 
     * else
     * if( keyStore != null )
     * setClient( (HttpsURLConnection) client , keyStore , keyPass , sslProto );
     * 
     */

    String disableTrustProto = opts.getOptString("disableTrust", null);

    if (disableTrustProto != null)
        disableTrust(client, disableTrustProto);

    String user = opts.getOptString("user", null);
    String pass = opts.getOptString("password", null);
    if (user != null && pass != null) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);

        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        /*
         * // Create AuthCache instance
         * AuthCache authCache = new BasicAuthCache();
         * // Generate DIGEST scheme object, initialize it and add it to the local
         * // auth cache
         * DigestScheme digestAuth = new DigestScheme();
         * // Suppose we already know the realm name
         * digestAuth.overrideParamter("realm", "some realm");
         * // Suppose we already know the expected nonce value
         * digestAuth.overrideParamter("nonce", "whatever");
         * authCache.put(host, digestAuth);
         * 
         * // Add AuthCache to the execution context
         * BasicHttpContext localcontext = new BasicHttpContext();
         * localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
         */

    }

}

From source file:com.googlecode.noweco.webmail.portal.bull.BullWebmailPortalConnector.java

public PortalConnection connect(final HttpHost proxy, final String user, final String password)
        throws IOException {
    DefaultHttpClient httpclient = UnsecureHttpClientFactory.INSTANCE.createUnsecureHttpClient(proxy);
    HttpPost httpost;//from w  w w.  ja v  a  2s  .  c o  m
    List<NameValuePair> nvps;
    HttpResponse rsp;
    int statusCode;
    HttpEntity entity;

    // mailbox does not appear with no FR language
    // with Mozilla actions are simple
    new ClientParamBean(httpclient.getParams()).setDefaultHeaders(Arrays.asList(
            (Header) new BasicHeader("Accept-Language", "fr-fr,fr;q=0.8,en;q=0.5,en-us;q=0.3"),
            new BasicHeader("User-Agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1")));

    String firstEntity = authent(httpclient, user, password);
    Matcher datasMatcher = DATAS.matcher(firstEntity);
    if (!datasMatcher.find()) {
        Matcher matcher = NEW_PASSWD.matcher(firstEntity);
        if (matcher.find()) {
            // try a bad password
            authent(httpclient, user, password + "BAD");
            // and retry good password (expired)
            firstEntity = authent(httpclient, user, password);
            datasMatcher = DATAS.matcher(firstEntity);
            if (!datasMatcher.find()) {
                throw new IOException("Unable to find Datas, after bad password try");
            }
        } else {
            throw new IOException("Unable to find Datas");
        }
    }

    // STEP 2 : WEB-MAIL

    httpost = new HttpPost("https://bullsentry.bull.fr:443/cgi/wway_cookie");
    nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("TdsName", "PILX"));
    nvps.add(new BasicNameValuePair("Proto", "s"));
    nvps.add(new BasicNameValuePair("Port", "443"));
    nvps.add(new BasicNameValuePair("Cgi", "cgi"));
    nvps.add(new BasicNameValuePair("Mode", "set"));
    nvps.add(new BasicNameValuePair("Total", "3"));
    nvps.add(new BasicNameValuePair("Current", "1"));
    nvps.add(new BasicNameValuePair("ProtoR", "s"));
    nvps.add(new BasicNameValuePair("PortR", "443"));
    nvps.add(new BasicNameValuePair("WebAgt", "1"));
    nvps.add(new BasicNameValuePair("UrlConnect", "https://telemail.bull.fr:443/"));
    nvps.add(new BasicNameValuePair("Service", "WEB-MAIL"));
    nvps.add(new BasicNameValuePair("Datas", datasMatcher.group(1)));

    Matcher lastCnxMatcher = LAST_CNX.matcher(firstEntity);
    if (!lastCnxMatcher.find()) {
        throw new IOException("Unable to find lastCnx");
    }
    nvps.add(new BasicNameValuePair("lastCnx", lastCnxMatcher.group(1)));
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // send the request
    rsp = httpclient.execute(httpost);
    statusCode = rsp.getStatusLine().getStatusCode();
    if (statusCode != 200) {
        throw new IOException("Unable to connect to bull portail, status code : " + statusCode);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.debug("STEP 2 Apps Cookie : {}", httpclient.getCookieStore().getCookies());
    }

    // free result resources
    entity = rsp.getEntity();
    if (entity != null) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("STEP 2 Entity : {}", EntityUtils.toString(entity));
        }
        EntityUtils.consume(entity);
    }

    // STEP 3 : telemail

    HttpGet httpGet = new HttpGet("https://telemail.bull.fr:443/HomePage.nsf");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    String secondEntity = EntityUtils.toString(entity);
    if (entity != null) {
        LOGGER.trace("STEP 3 Entity : {}", secondEntity);
        EntityUtils.consume(entity);
    }

    Matcher nsfMatcher = PATTERN.matcher(secondEntity);
    if (!nsfMatcher.find()) {
        throw new IOException("Unable to find nsf");
    }

    String pathPrefix = nsfMatcher.group(3).replace('\\', '/');
    LOGGER.debug("pathPrefix : {}", pathPrefix);

    String protocol = nsfMatcher.group(1);
    int port;
    if ("http".equals(protocol)) {
        port = 80;
    } else if ("https".equals(protocol)) {
        port = 443;
    } else {
        throw new IOException("Unknown protocol " + protocol);
    }
    return new DefaultPortalConnection(httpclient, new HttpHost(nsfMatcher.group(2), port, protocol),
            pathPrefix);
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java

private static void configureAuthentication(final DefaultHttpClient httpClient, final String proxyHost,
        final int proxyPort, final RemoteAuthenticationSettings ras) {
    if (ras != null) {
        List<String> authorisationPreference = new ArrayList<String>(2);
        authorisationPreference.add(AuthPolicy.DIGEST);
        authorisationPreference.add(AuthPolicy.BASIC);

        Credentials credentials = null;/* w  w  w.j a va 2s . com*/

        if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthPolicy.NTLM);

            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());

        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    credentials);
        }

        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference);
    }
}

From source file:fm.last.android.player.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;// w w w .j a v  a  2  s  .co  m
    }
    Log.d(LOG_TAG, "processing");
    String url = request.getRequestLine().getUri();

    DefaultHttpClient seed = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(), registry);
    DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
    HttpGet method = new HttpGet(url);
    for (Header h : request.getAllHeaders()) {
        method.addHeader(h);
    }
    HttpResponse realResponse = null;
    try {
        Log.d(LOG_TAG, "starting download");
        realResponse = http.execute(method);
        Log.d(LOG_TAG, "downloaded");
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Error downloading", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error downloading", e);
    }

    if (realResponse == null) {
        return;
    }

    if (!isRunning)
        return;

    Log.d(LOG_TAG, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(LOG_TAG, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");
    Log.d(LOG_TAG, "headers done");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(LOG_TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start streaming content.
        byte[] buff = new byte[8192];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        mgr.shutdown();
        client.close();
        Log.d(LOG_TAG, "streaming complete");
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void setHttpClientProxy(DefaultHttpClient client, String url, String proxyUser,
        String proxyPassword) {/*w w w.  j av  a  2  s . c  om*/
    String proxyHost = null;
    int proxyPort = 8080;
    try {
        System.setProperty("java.net.useSystemProxies", "true");
        URI uri = new URI(url);
        List<Proxy> proxies = ProxySelector.getDefault().select(uri);
        if (proxies != null && client != null) {
            for (Proxy proxy : proxies) {
                if (proxy.address() != null && proxy.address() instanceof InetSocketAddress) {
                    InetSocketAddress address = (InetSocketAddress) proxy.address();
                    proxyHost = address.getHostName();
                    HttpHost host = new HttpHost(address.getHostName(), address.getPort());
                    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        Debug.log(ex);
    }

    if (proxyHost == null && System.getProperty("http.proxyHost") != null
            && !"".equals(System.getProperty("http.proxyHost"))) {
        proxyHost = System.getProperty("http.proxyHost");
        try {
            proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
        } catch (Exception ex) {
            //ignore
        }
        HttpHost host = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
    }

    if (proxyUser != null) {
        BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        bcp.setCredentials(new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(proxyUser, proxyPassword));
        client.setCredentialsProvider(bcp);
    }
}

From source file:com.farmafene.commons.cas.URLAuthenticationHandler.java

/**
 * {@inheritDoc}//from   w  w  w  .j ava2 s . com
 * 
 * @see org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler#authenticateUsernamePasswordInternal(org.jasig.cas.authentication.principal.UsernamePasswordCredentials)
 */
@Override
protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials)
        throws AuthenticationException {
    long initTime = System.currentTimeMillis();
    boolean authenticateUsernamePasswordInternal = false;
    HttpContext context = new BasicHttpContext();
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(loginURL);
    f.setProxyHost(proxyHost);
    f.setProxyPort(proxyPort);
    DefaultHttpClient httpClient = f.getClient();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    org.apache.http.auth.UsernamePasswordCredentials cred = new org.apache.http.auth.UsernamePasswordCredentials(
            credentials.getUsername(), credentials.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, cred);
    List<String> n = new ArrayList<String>();
    n.add(AuthPolicy.BASIC);
    n.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, n);
    context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    HttpGet httpGet = new HttpGet(loginURL);
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet, context);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            authenticateUsernamePasswordInternal = true;
        }
    } catch (ClientProtocolException e) {
        logger.error("Error: ", e);
    } catch (IOException e) {
        logger.error("Error: ", e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Total time: " + (System.currentTimeMillis() - initTime) + " ms, " + this);
    }
    return authenticateUsernamePasswordInternal;
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Creates a new {@code HttpClient} instance.
 *
 * @param settings The settings to use for setting up the client or {@code null}.
 * @param url The {@code URL} to use for setting up the client or {@code null}.
 *
 * @return A new {@code HttpClient} instance.
 *
 * @see #DEFAULT_TIMEOUT// w w  w. j  a  v a  2s .c o m
 * @since 2.8
 */
private static HttpClient createHttpClient(Settings settings, URL url) {
    DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // Some web servers don't allow the default user-agent sent by httpClient
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    if (settings != null && settings.getActiveProxy() != null) {
        Proxy activeProxy = settings.getActiveProxy();

        ProxyInfo proxyInfo = new ProxyInfo();
        proxyInfo.setNonProxyHosts(activeProxy.getNonProxyHosts());

        if (StringUtils.isNotEmpty(activeProxy.getHost())
                && (url == null || !ProxyUtils.validateNonProxyHosts(proxyInfo, url.getHost()))) {
            HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (StringUtils.isNotEmpty(activeProxy.getUsername()) && activeProxy.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(activeProxy.getUsername(),
                        activeProxy.getPassword());

                httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            }
        }
    }

    return httpClient;
}