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

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

Introduction

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

Prototype

public static void setVersion(HttpParams httpParams, ProtocolVersion protocolVersion) 

Source Link

Usage

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

public RSSFeed getRSSChannelInfo(String url) {

    // Parse url//w w w.j  a va2 s. c  om
    Uri uri = Uri.parse(url);
    int event;
    String text = null;
    String torrent = null;
    boolean header = true;

    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);

    //        Log.d("Debug", "Host: " + uri.getAuthority());

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

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

    httpclient.setParams(httpParameters);

    RSSFeed rssFeed = new RSSFeed();

    try {

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

        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;
        List<RSSFeedItem> items = new ArrayList<RSSFeedItem>();

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

            name = xmlParser.getName();

            switch (event) {
            case XmlPullParser.START_TAG:

                if (name != null && name.equals("item")) {
                    header = false;
                }

                break;

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

            case XmlPullParser.END_TAG:

                if (name.equals("title")) {
                    if (header) {
                        rssFeed.setChannelTitle(text);
                    }
                } else if (name.equals("description")) {
                    if (header) {
                    }
                } else if (name.equals("link")) {
                    if (header) {
                        rssFeed.setChannelLink(text);
                    }

                }

                break;
            }

            event = xmlParser.next();

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

    // return JSON String
    return rssFeed;

}

From source file:com.eastedge.readnovel.weibo.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*from   www .  j a  v a  2s.  c  om*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:org.dasein.cloud.cloudsigma.CloudSigmaMethod.java

private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new NoContextException();
    }/*from ww  w .j a  v a 2 s. c  o  m*/
    boolean ssl = uri.getScheme().startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    return new DefaultHttpClient(params);
}

From source file:net.lamp.support.HttpManager.java

private static HttpClient getNewHttpClient() {
    try {//from  w  w w  .  j a v a2  s . co m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        // if (NetState.Mobile == NetStateManager.CUR_NETSTATE) {
        // // ??APN?            // HttpHost proxy = NetStateManager.getAPN();
        // if (null != proxy) {
        // client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
        // proxy);
        // }
        // }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();

    final String ids_string = getMediaIds(pics, twitter);

    if (ids_string == null) {
        return false;
    }// w w w  .  j a va 2  s .co  m

    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                        twitter_endpoint_path);

                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);

                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message",
                        "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {

    }
    return true;
}

From source file:cn.edu.mju.Thriphoto.net.HttpManager.java

private static HttpClient getNewHttpClient() {
    try {// w w w.j  a  va2s.  co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        // if (NetState.Mobile == NetStateManager.CUR_NETSTATE) {
        // // ??APN
        // HttpHost proxy = NetStateManager.getAPN();
        // if (null != proxy) {
        // client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
        // proxy);
        // }
        // }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {//from ww  w .  j  av  a 2s  .  c o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            // ??APN
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:de.codesourcery.eve.apiclient.AbstractHttpAPIClient.java

private ThreadSafeClientConnManager getConnectionManager() {
    if (connectionManager == null) {
        // Create and initialize HTTP parameters
        final HttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 30);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        // setup SSL
        try {//ww  w.  j  av  a 2 s . co  m
            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } }, new SecureRandom());

            SSLSocketFactory sf = new SSLSocketFactory(sslContext);
            Scheme httpsScheme = new Scheme("https", 443, sf);
            schemeRegistry.register(httpsScheme);
        } catch (Exception e) {
            LOG.error("getConnectionManager(): Failed to setup SSL protocol for http client", e);
            throw new RuntimeException(e);
        }

        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    }
    return connectionManager;
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static HttpClient getDefaultHttpsClient() {
    try {//  w w w.j  a  va2  s. c  o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        HttpClientBuilder b = HttpClientBuilder.create();
        return b.build();
        //return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java

/**
 * Creates default params for the Apache HTTP Client.
 *///  w  ww.ja  va  2  s .  co  m
protected HttpParams createDefaultHttpParams(BindingSession session) {
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params,
            (String) session.get(SessionParameter.USER_AGENT, ClientVersion.OPENCMIS_USER_AGENT));
    HttpProtocolParams.setContentCharset(params, IOUtils.UTF8);
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpConnectionParams.setStaleCheckingEnabled(params, true);

    int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
    if (connectTimeout >= 0) {
        HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
    }

    int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
    if (readTimeout >= 0) {
        HttpConnectionParams.setSoTimeout(params, readTimeout);
    }

    return params;
}