Example usage for org.apache.http.params HttpProtocolParams setUserAgent

List of usage examples for org.apache.http.params HttpProtocolParams setUserAgent

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setUserAgent.

Prototype

public static void setUserAgent(HttpParams httpParams, String str) 

Source Link

Usage

From source file:com.worthed.googleplus.HttpUtils.java

private HttpClient getHttpClient() {
    //  HttpParams ? HTTP ??
    HttpParams httpParams = new BasicHttpParams();

    //  Socket ? Socket ?
    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    // ??? true/*from www  . jav a2  s  . com*/
    HttpClientParams.setRedirecting(httpParams, true);

    //  user agent
    String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
    HttpProtocolParams.setUserAgent(httpParams, userAgent);

    //  HttpClient 
    // ? HttpClient httpClient = new HttpClient(); Commons HttpClient
    //  Android 1.5 ? Apache ? DefaultHttpClient
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    return httpClient;
}

From source file:com.github.ignition.support.http.IgnitedHttpClient.java

protected void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_READ_STREAM_TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_HTTP_USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (DiagnosticSupport.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {//w  w w.  j  ava2  s . co  m
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);

}

From source file:com.applicake.beanstalkclient.utils.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*  w ww .  j  a  v a 2 s .c o  m*/
 * @param userAgent
 *          to report in your HTTP requests.
 * @param sessionCache
 *          persistent session cache
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    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);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:cn.edu.szjm.support.http.IgnitedHttp.java

protected void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_HTTP_USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (IgnitedDiagnostics.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {/*w  w w  .jav a2  s. c  o  m*/
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);
}

From source file:com.vuze.android.remote.rpc.RPC.java

public static boolean isLocalAvailable() {
    Object oldThreadPolicy = null;
    try {//  w  w  w .j  a v a  2s . c om
        if (android.os.Build.VERSION.SDK_INT > 9) {
            // allow synchronous networking because we are only going to localhost
            // and it will return really fast (it better!)
            oldThreadPolicy = enableNasty();
        }

        String url = "http://localhost:9091/transmission/rpc?json="
                + URLEncoder.encode("{\"method\":\"session-get\"}", "utf-8");

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");
        HttpConnectionParams.setConnectionTimeout(basicHttpParams, 200);
        HttpConnectionParams.setSoTimeout(basicHttpParams, 900);
        HttpClient httpclient = new DefaultHttpClient(basicHttpParams);

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); // IllegalArgumentException

        // Execute the request
        HttpResponse response = httpclient.execute(httpget);

        if (response.getStatusLine().getStatusCode() == 409) {
            // Must be RPC!
            return true;
        }

    } catch (HttpHostConnectException ignore) {
        // Connection to http://localhost:9091 refused
    } catch (Throwable e) {
        Log.e("RPC", "isLocalAvailable", e);
    } finally {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            revertNasty((ThreadPolicy) oldThreadPolicy);
        }
    }
    return false;
}

From source file:org.muckebox.android.net.MuckeboxHttpClient.java

private void setUserAgent() {
    String userAgent = String.format("%s (%s %s; %s; %s)",
            Muckebox.getAppContext().getString(R.string.user_agent), android.os.Build.MANUFACTURER,
            android.os.Build.MODEL, android.os.Build.ID, android.os.Build.SERIAL);

    HttpProtocolParams.setUserAgent(mHttpClient.getParams(), userAgent);
}

From source file:org.jets3t.service.utils.signedurl.GatekeeperClientUtils.java

/**
 * Prepares objects for HTTP communications with the Gatekeeper servlet.
 * @return//  w w  w. j  av  a2  s  .com
 */
private HttpClient initHttpConnection() {
    // Set client parameters.
    HttpParams params = RestUtils.createDefaultHttpParams();
    HttpProtocolParams.setUserAgent(params, ServiceUtils.getUserAgentDescription(userAgentDescription));

    // Set connection parameters.
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, connectionTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    // Replace default error retry handler.
    httpClient.setHttpRequestRetryHandler(new RestUtils.JetS3tRetryHandler(maxRetryCount, null));

    // httpClient.getParams().setAuthenticationPreemptive(true);
    httpClient.setCredentialsProvider(credentialsProvider);

    return httpClient;
}

From source file:com.shwy.bestjoy.utils.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 *///from  w  w  w  .j a  v  a  2 s.c o  m
public static HttpClient newInstance(String userAgent) {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sslSocketFactory = new SSLSocketFactoryEx(trustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();

        // Turn off stale checking.  Our connections break all the time anyway,
        // and it's not worth it to pay the penalty of checking every time.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // Default connection and socket timeout of 20 seconds.  Tweak to taste.
        HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);
        HttpConnectionParams.setSoTimeout(params, 60 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        // Don't handle redirects -- return them to the caller.  Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, true);

        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, userAgent);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
        // We use a factory method to modify superclass initialization
        // parameters without the funny call-a-static-method dance.
        return new AndroidHttpClient(manager, params);
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return new DefaultHttpClient();

}

From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java

public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) {

    // Decode url link
    try {//  w  ww  . j  a v  a  2s  . c  o  m
        channelUrl = URLDecoder.decode(channelUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString());
    }

    // Parse url
    Uri uri = uri = Uri.parse(channelUrl);
    ;
    int event;
    String text = null;
    String torrent = null;
    boolean header = true;

    // TODO delete itemCount, as it's not really used
    this.itemCount = 0;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    XmlPullParserFactory xmlFactoryObject;
    XmlPullParser xmlParser = null;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    RSSFeed rssFeed = new RSSFeed();
    rssFeed.setChannelTitle(channelTitle);
    rssFeed.setChannelLink(channelUrl);

    httpclient = null;

    try {

        // Making HTTP request
        HttpHost targetHost = new HttpHost(uri.getAuthority());

        // httpclient = new DefaultHttpClient(httpParameters);
        // httpclient = new DefaultHttpClient();
        httpclient = getNewHttpClient();

        httpclient.setParams(httpParameters);

        //            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        //            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        //
        //            httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        HttpGet httpget = new HttpGet(channelUrl);

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        xmlFactoryObject = XmlPullParserFactory.newInstance();
        xmlParser = xmlFactoryObject.newPullParser();

        xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        xmlParser.setInput(is, null);

        event = xmlParser.getEventType();

        // Get Channel info
        String name;
        RSSFeedItem item = null;
        ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>();

        // Get items
        while (event != XmlPullParser.END_DOCUMENT) {

            name = xmlParser.getName();

            switch (event) {
            case XmlPullParser.START_TAG:

                if (name != null && name.equals("item")) {
                    header = false;
                    item = new RSSFeedItem();
                    itemCount = itemCount + 1;
                }

                try {
                    for (int i = 0; i < xmlParser.getAttributeCount(); i++) {

                        if (xmlParser.getAttributeName(i).equals("url")) {
                            torrent = xmlParser.getAttributeValue(i);

                            if (torrent != null) {
                                torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8"));
                            }
                            break;
                        }
                    }
                } catch (Exception e) {

                }

                break;

            case XmlPullParser.TEXT:
                text = xmlParser.getText();
                break;

            case XmlPullParser.END_TAG:

                if (name.equals("title")) {
                    if (!header) {
                        item.setTitle(text);
                        //                                Log.d("Debug", "PARSER - Title: " + text);
                    }
                } else if (name.equals("description")) {
                    if (header) {
                        //                                Log.d("Debug", "Channel Description: " + text);
                    } else {
                        item.setDescription(text);
                        //                                Log.d("Debug", "Description: " + text);
                    }
                } else if (name.equals("link")) {
                    if (!header) {
                        item.setLink(text);
                        //                                Log.d("Debug", "Link: " + text);
                    }

                } else if (name.equals("pubDate")) {

                    // Set item pubDate
                    if (item != null) {
                        item.setPubDate(text);
                    }

                } else if (name.equals("enclosure")) {
                    item.setTorrentUrl(torrent);
                    //                            Log.d("Debug", "Enclosure: " + torrent);
                } else if (name.equals("item") && !header) {

                    if (items != null & item != null) {

                        // Fix torrent url for no-standard rss feeds
                        if (torrent == null) {

                            String link = item.getLink();

                            if (link != null) {
                                link = Uri.decode(URLEncoder.encode(link, "UTF-8"));
                            }

                            item.setTorrentUrl(link);
                        }

                        items.add(item);
                    }

                }

                break;
            }

            event = xmlParser.next();

            //                if (!header) {
            //                    items.add(item);
            //                }

        }

        // Filter items

        //            Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<");
        if (filter != null && !filter.equals("")) {

            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {

                item = (RSSFeedItem) iterator.next();

                // If link doesn't match filter, remove it
                //                    Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<");

                Pattern patter = Pattern.compile(filter);

                Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object

                if (!(matcher.find())) {
                    iterator.remove();
                }

            }
        }

        rssFeed.setItems(items);
        rssFeed.setItemCount(itemCount);
        rssFeed.setChannelPubDate(items.get(0).getPubDate());
        rssFeed.setResultOk(true);

        is.close();
    } catch (Exception e) {
        Log.e("Debug", "RSSFeedParser - : " + e.toString());
        rssFeed.setResultOk(false);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }

    // return JSON String
    return rssFeed;

}

From source file:com.photowall.oauth.util.BaseHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @param sessionCache persistent session cache
 * @return AndroidHttpClient for you to use for all your requests.
 *//*from   www  .jav a 2s . co  m*/
public static BaseHttpClient newInstance(Context mContext, String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    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);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new BaseHttpClient(mContext, manager, params);
}