Example usage for org.apache.http.conn.params ConnRouteParams setDefaultProxy

List of usage examples for org.apache.http.conn.params ConnRouteParams setDefaultProxy

Introduction

In this page you can find the example usage for org.apache.http.conn.params ConnRouteParams setDefaultProxy.

Prototype

public static void setDefaultProxy(final HttpParams params, final HttpHost proxy) 

Source Link

Document

Sets the ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY parameter value.

Usage

From source file:com.seajas.search.contender.http.ParameterizableHttpClient.java

/**
 * Default constructor.//  ww  w.j a  v  a  2s .  co  m
 * 
 * @param connectionManager
 * @param parameters
 * @param httpHost
 * @param httpPort
 * @param userAgent
 * @param connectionTimeout
 */
public ParameterizableHttpClient(final ClientConnectionManager connectionManager, final HttpParams parameters,
        final String httpHost, final Integer httpPort, final String userAgent,
        final Integer connectionTimeout) {
    super(connectionManager, parameters);

    if (!StringUtils.isEmpty(httpHost))
        ConnRouteParams.setDefaultProxy(getParams(), new HttpHost(httpHost, httpPort));
    HttpProtocolParams.setUserAgent(getParams(), userAgent);

    if (connectionTimeout > 0) {
        HttpConnectionParams.setSoTimeout(getParams(), connectionTimeout);
        HttpConnectionParams.setConnectionTimeout(getParams(), connectionTimeout);
        HttpClientParams.setConnectionManagerTimeout(getParams(), connectionTimeout);
    }

    setRedirectStrategy(new DefaultRedirectStrategy());
}

From source file:com.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java

public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) {
    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.unregister("https");
    try {/*from w ww. j ava 2s  .com*/
        SSLContext instance = SSLContext.getInstance("TLS");
        TrustManager tm = UnsecureX509TrustManager.INSTANCE;
        instance.init(null, new TrustManager[] { tm }, null);
        schemeRegistry.register(new Scheme("https", 443,
                new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    } catch (Exception e) {
        throw new RuntimeException("TLS issue", e);
    }
    httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies());
    HttpParams params = httpclient.getParams();
    if (proxy != null) {
        ConnRouteParams.setDefaultProxy(params, proxy);
    }
    HttpConnectionParams.setSoTimeout(params, 7000);
    return httpclient;
}

From source file:com.android.xbrowser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    HttpHost httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    if (httpHost != null) {
        ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    }//from w  w  w.ja v a  2  s .  com
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:org.apache.nifi.processors.gcp.ProxyAwareTransportFactory.java

@Override
public HttpTransport create() {

    if (proxyConfig == null) {
        return DEFAULT_TRANSPORT;
    }//from   ww  w .j  a  va 2s . co  m

    final Proxy proxy = proxyConfig.createProxy();

    if (Proxy.Type.HTTP.equals(proxy.type()) && proxyConfig.hasCredential()) {
        // If it requires authentication via username and password, use ApacheHttpTransport
        final String host = proxyConfig.getProxyServerHost();
        final int port = proxyConfig.getProxyServerPort();
        final HttpHost proxyHost = new HttpHost(host, port);

        final DefaultHttpClient httpClient = new DefaultHttpClient();
        ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxyHost);

        if (proxyConfig.hasCredential()) {
            final AuthScope proxyAuthScope = new AuthScope(host, port);
            final UsernamePasswordCredentials proxyCredential = new UsernamePasswordCredentials(
                    proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword());
            final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredential);
            httpClient.setCredentialsProvider(credentialsProvider);
        }

        return new ApacheHttpTransport(httpClient);

    }

    return new NetHttpTransport.Builder().setProxy(proxy).build();
}

From source file:com.android.internal.location.GpsXtraDownloader.java

protected static byte[] doDownload(String url, boolean isProxySet, String proxyHost, int proxyPort) {
    AndroidHttpClient client = null;/*from  ww w. j a va 2s .  c  o m*/
    try {
        client = AndroidHttpClient.newInstance("Android");
        HttpUriRequest req = new HttpGet(url);

        if (isProxySet) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
        }

        req.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        req.addHeader("x-wap-profile",
                "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#");

        HttpResponse response = client.execute(req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            Log.d(TAG, "HTTP error: " + status.getReasonPhrase());
            return null;
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Unexpected IOException.", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (Exception e) {
        Log.d(TAG, "error " + e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:com.android.server.location.GpsXtraDownloader.java

protected static byte[] doDownload(String url, boolean isProxySet, String proxyHost, int proxyPort) {
    if (DEBUG)//from   www  .java2 s. c om
        Log.d(TAG, "Downloading XTRA data from " + url);

    AndroidHttpClient client = null;
    try {
        client = AndroidHttpClient.newInstance("Android");
        HttpUriRequest req = new HttpGet(url);

        if (isProxySet) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
        }

        req.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        req.addHeader("x-wap-profile",
                "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#");

        HttpResponse response = client.execute(req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            if (DEBUG)
                Log.d(TAG, "HTTP error: " + status.getReasonPhrase());
            return null;
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Unexpected IOException.", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (Exception e) {
        if (DEBUG)
            Log.d(TAG, "error " + e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:org.thoughtcrime.securesms.mms.MmsCommunication.java

protected static HttpClient constructHttpClient(MmsConnectionParameters mmsConfig) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "TextSecure/0.1");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    if (mmsConfig.hasProxy()) {
        ConnRouteParams.setDefaultProxy(params, new HttpHost(mmsConfig.getProxy(), mmsConfig.getPort()));
    }//from w  w w  . ja v  a2 s  .  co m

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(manager, params);
}

From source file:ch.cyberduck.core.http.HTTP4Session.java

/**
 * Create new HTTP client with default configuration and custom trust manager.
 *
 * @return A new instance of a default HTTP client.
 *//*ww  w. j av  a 2s .  co m*/
protected AbstractHttpClient http() {
    if (null == http) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, "ISO-8859-1");

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme("http", host.getPort(), PlainSocketFactory.getSocketFactory()));
        if ("https".equals(this.getHost().getProtocol().getScheme())) {
            org.apache.http.conn.ssl.SSLSocketFactory factory = new SSLSocketFactory(
                    new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                    org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            registry.register(new Scheme(host.getProtocol().getScheme(), host.getPort(), factory));
        }
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.instance();
            if ("https".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if ("http".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        ClientConnectionManager manager = new SingleClientConnManager(registry);
        http = new DefaultHttpClient(manager, params);
        this.configure(http);
    }
    return http;
}

From source file:com.android.mms.service.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD./*from  ww w  . ja v a 2  s  . c om*/
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @param isProxySet If proxy is set
 * @param proxyHost The host of the proxy
 * @param proxyPort The port of the proxy
 * @param resolver The custom name resolver to use
 * @param useIpv6 If we should use IPv6 address when the HTTP client resolves the host name
 * @param mmsConfig The MmsConfig to use
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws com.android.mms.service.exception.MmsHttpException if HTTP request gets error response (>=400)
 */
public static byte[] httpConnection(Context context, String url, byte[] pdu, int method, boolean isProxySet,
        String proxyHost, int proxyPort, NameResolver resolver, boolean useIpv6, MmsConfig.Overridden mmsConfig)
        throws MmsHttpException {
    final String methodString = getMethodString(method);
    Log.v(TAG,
            "HttpUtils: request param list\n" + "url=" + url + "\n" + "method=" + methodString + "\n"
                    + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort="
                    + proxyPort + "\n" + "size=" + (pdu != null ? pdu.length : 0));

    NetworkAwareHttpClient client = null;
    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        client = createHttpClient(context, resolver, useIpv6, mmsConfig);
        HttpRequest req = null;

        switch (method) {
        case HTTP_POST_METHOD:
            ByteArrayEntity entity = new ByteArrayEntity(pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);

        // UA Profile URL header
        String xWapProfileTagName = mmsConfig.getUaProfTagName();
        String xWapProfileUrl = mmsConfig.getUaProfUrl();
        if (xWapProfileUrl != null) {
            Log.v(TAG, "HttpUtils: xWapProfUrl=" + xWapProfileUrl);
            req.addHeader(xWapProfileTagName, xWapProfileUrl);
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value. And replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsNaiKey() with the users NAI(Network Access Identifier)
        // inside the value.
        String extraHttpParams = mmsConfig.getHttpParams();

        if (!TextUtils.isEmpty(extraHttpParams)) {
            // Parse the parameter list
            String paramList[] = extraHttpParams.split("\\|");
            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);
                if (splitPair.length == 2) {
                    final String name = splitPair[0].trim();
                    final String value = resolveMacro(context, splitPair[1].trim(), mmsConfig);
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault()));

        final HttpResponse response = client.execute(target, req);
        final StatusLine status = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        Log.d(TAG,
                "HttpUtils: status=" + status + " size=" + (entity != null ? entity.getContentLength() : -1));
        for (Header header : req.getAllHeaders()) {
            if (header != null) {
                Log.v(TAG, "HttpUtils: header " + header.getName() + "=" + header.getValue());
            }
        }
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.d(TAG, "HttpUtils: transfer encoding is chunked");
                    int bytesTobeRead = mmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "HttpUtils: error reading input stream", e);
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.d(TAG, "HttpUtils: Chunked response length " + offset);
                        } else {
                            Log.e(TAG, "HttpUtils: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "HttpUtils: Error closing input stream", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            StringBuilder sb = new StringBuilder();
            if (body != null) {
                sb.append("response: text=").append(new String(body)).append('\n');
            }
            for (Header header : req.getAllHeaders()) {
                if (header != null) {
                    sb.append("req header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            for (Header header : response.getAllHeaders()) {
                if (header != null) {
                    sb.append("resp header: ").append(header.getName()).append('=').append(header.getValue())
                            .append('\n');
                }
            }
            Log.e(TAG,
                    "HttpUtils: error response -- \n" + "mStatusCode=" + status.getStatusCode() + "\n"
                            + "reason=" + status.getReasonPhrase() + "\n" + "url=" + url + "\n" + "method="
                            + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost
                            + "\n" + "proxyPort=" + proxyPort + (sb != null ? "\n" + sb.toString() : ""));
            throw new MmsHttpException(status.getReasonPhrase());
        }
        return body;
    } catch (IOException e) {
        Log.e(TAG, "HttpUtils: IO failure", e);
        throw new MmsHttpException(e);
    } catch (URISyntaxException e) {
        Log.e(TAG, "HttpUtils: invalid url " + url);
        throw new MmsHttpException("Invalid url " + url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.android.xbrowser.DownloadTouchIcon.java

@Override
public Void doInBackground(String... values) {
    if (mContentResolver != null) {
        mCursor = Bookmarks.queryCombinedForUrl(mContentResolver, mOriginalUrl, mUrl);
    }/*from   w w w .  ja  va  2 s  .co  m*/

    boolean inDatabase = mCursor != null && mCursor.getCount() > 0;

    String url = values[0];

    if (inDatabase || mMessage != null) {
        AndroidHttpClient client = null;
        HttpGet request = null;

        try {
            client = AndroidHttpClient.newInstance(mUserAgent);
            HttpHost httpHost = Proxy.getPreferredHttpHost(mContext, url);
            if (httpHost != null) {
                ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
            }

            request = new HttpGet(url);

            // Follow redirects
            HttpClientParams.setRedirecting(client.getParams(), true);

            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream content = entity.getContent();
                    if (content != null) {
                        Bitmap icon = BitmapFactory.decodeStream(content, null, null);
                        if (inDatabase) {
                            storeIcon(icon);
                        } else if (mMessage != null) {
                            Bundle b = mMessage.getData();
                            b.putParcelable(BrowserContract.Bookmarks.TOUCH_ICON, icon);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            if (request != null) {
                request.abort();
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

    if (mCursor != null) {
        mCursor.close();
    }

    if (mMessage != null) {
        mMessage.sendToTarget();
    }

    return null;
}