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.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException,
        JSONException {/*from  ww w .  j  a  v  a  2s  .  c  om*/
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}

From source file:com.haoqee.chat.net.Utility.java

public static HttpClient getNewHttpClient(long timeout) {
    try {//w w w . j a va2 s .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.);

        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);
        long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout;
        HttpConnectionParams.setSoTimeout(params, (int) soc_time);
        HttpClient client = new DefaultHttpClient(ccm, params);
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.yozio.android.Yozio.java

static HttpClient threadSafeHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    return new DefaultHttpClient(cm, params);
}

From source file:bkampfbot.Instance.java

/**
 * Fhrt die aktuelle Instans aus//from   w  ww .j  av  a2  s  . c o  m
 * 
 * @throws ClientProtocolException
 * @throws IOException
 * @throws FatalError
 * @throws JSONException
 * @throws RestartLater
 * @throws NoSuchAlgorithmException
 */
public final void run() throws FatalError, RestartLater {

    // initialization HTTP client

    this.httpclient = new DefaultHttpClient();

    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    HttpProtocolParams.setUserAgent(params, Config.getUserAgent());

    this.httpclient.setParams(params);

    if (Config.getProxyHost() != null && Config.getProxyPort() != 0) {
        if (Config.getProxyUsername() != null && Config.getProxyPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(Config.getProxyHost(), Config.getProxyPort()),
                    new UsernamePasswordCredentials(Config.getProxyUsername(), Config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(Config.getProxyHost(), Config.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    }

    this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    switch (this.modus) {
    // default: do nothing
    default:
        break;

    // call help
    case help:
        Output.help();
        System.exit(0);
        break;

    // call proxy test
    case testproxy:
        new TestProxy();
        System.exit(0);
        break;

    }
    // login
    this.login();
    this.switchToSpeedHost();

    switch (this.modus) {

    // for things without login
    case help:
    case testproxy:
        break;

    case daily:

        for (Daily d : this.daily) {

            if (d == null)
                break;

            switch (d) {
            // call "Rubbellos"
            case scratchTicket:
                ScratchTicket.getInstance().run();
                break;

            // call "Tagesquiz"
            case quiz:
                Quiz.getInstance().run();
                break;

            // call "Lotto"
            case glueck:
                Gluecksrad.getInstance().run();
                break;

            // call "Weinfsser"
            case wein:
                Wein.getInstance().run();
                break;

            // call "Tagesspiel"
            case spiel:
                Tagesspiel.getInstance().run();
                break;

            // call "Tagesspiel"
            case spielZwerg:
                Tagesspiel.getInstance(true).run();
                break;

            // call "Wrterjagd"
            case jagd:
                Jagd.getInstance().run();
                break;

            }
        }
        Control.safeExit();
        break;

    // call "Lotto"
    case lottery:
        Lottery.getInstance().run();
        Control.safeExit();
        break;

    // call "Pins"
    case pins:
        Pins.getInstance().run();
        Control.safeExit();
        break;

    // call "Plan"
    default:
    case normal:

        if (Config.getPlan0() == null && Config.getPlan1() == null) {
            Output.printTabLn("Beide Plne sind leer. " + "Bitte berprfen Sie die Konfiguration.", 0);
            System.exit(1);
        }

        Calendar lastCall = null;
        while (true) {
            Calendar now = new GregorianCalendar();
            now.setTime(Config.getDate());
            now.add(Calendar.MINUTE, -2);
            if (lastCall != null && lastCall.after(now)) {
                Output.println("Der Bot war bei der Abarbeitung der Plne zu schnell. "
                        + "Vermutlich trat ein Fehler auf. Damit wir nicht auffallen, "
                        + "warten wir 5 Minuten.", 1);

                Control.sleep(3000);

            }
            lastCall = new GregorianCalendar();
            this.runPlans();

            Control.sleep(5);

            this.getCharacter();

            Control.sleep(5);

        }
    }
}

From source file:com.haoqee.chatsdk.net.Utility.java

public static HttpClient getNewHttpClient(long timeout) {
    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.);

        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);
        long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout;
        HttpConnectionParams.setSoTimeout(params, (int) soc_time);
        HttpClient client = new DefaultHttpClient(ccm, params);
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;//from  www  .j av a 2 s  .  com

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    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, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

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

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

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

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + 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();
    }

}

From source file:org.dasein.cloud.tier3.APIHandler.java

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

    if (ctx == null) {
        throw new NoContextException();
    }/*from   w w w . j a  v a2  s . co m*/

    boolean ssl = uri.getScheme().startsWith("https");

    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // noinspection deprecation
    HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString());
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

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

From source file:com.curso.listadapter.net.RESTClient.java

/**
 *
 * this private method obtains the httpclient that support https
 * and set the timeout in 30 secconds//from w  w w . j a v a2s .  c  om
 *
 *
 * */
public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, RequestTimeOut);
        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);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.pc.dailymile.DailyMileClient.java

private void initHttpClient() {
    HttpParams parameters = new BasicHttpParams();
    HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
    // set the User-Agent to a common User-Agent because currently
    // the default httpclient User-Agent doesn't work with dailymile
    HttpProtocolParams.setUserAgent(parameters, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
    HttpProtocolParams.setUseExpectContinue(parameters, false);
    HttpConnectionParams.setTcpNoDelay(parameters, true);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(tsccm, parameters);
    defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }// w  ww.ja  v  a  2  s.c o  m
        }
    });

    defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });
    httpClient = defaultHttpClient;
}