Example usage for org.apache.http.params HttpParams setParameter

List of usage examples for org.apache.http.params HttpParams setParameter

Introduction

In this page you can find the example usage for org.apache.http.params HttpParams setParameter.

Prototype

HttpParams setParameter(String str, Object obj);

Source Link

Usage

From source file:website.openeng.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;/*from w w  w . ja v a2 s . com*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(KanjiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "KanjiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:jp.ambrosoli.quickrestclient.apache.service.ApacheHttpService.java

/**
 * ???//www  .j a  v  a 2s . c o m
 * 
 * @param httpParams
 *            HttpParams
 * @param proxy
 *            ?
 */
protected void setProxy(final HttpParams httpParams, final ProxyInfo proxy) {
    if (proxy == null) {
        return;
    }
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
}

From source file:io.mandrel.requests.http.ApacheHttpRequester.java

public HttpUriRequest prepareRequest(Uri uri, Spider spider) {
    Builder builder = RequestConfig.copy(defaultRequestConfig);

    HttpGet request = new HttpGet(uri.toURI());

    // Add headers, cookies and ohter stuff
    if (headers() != null) {
        headers().forEach(header -> {
            if (header != null) {
                request.addHeader(header.getName(), header.getValue());
            }//from  w w w  .  j  av a  2s .  com
        });
    }

    HttpParams params = new BasicHttpParams();
    if (params() != null) {
        params().forEach(param -> {
            if (param != null) {
                params.setParameter(param.getName(), param.getValue());
            }
        });
    }
    request.setParams(params);

    // Configure the user -agent
    String userAgent = userAgentProvisionner().get(uri.toString(), spider);
    if (Strings.isNullOrEmpty(userAgent)) {
        request.addHeader(HttpHeaders.USER_AGENT, userAgent);
    }

    // Configure the proxy
    ProxyServer proxy = proxyServersSource().findProxy(spider);
    if (proxy != null) {
        // TODO Auth!
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol().getProtocol());
        builder.setProxy(proxyHost);
    }

    request.setConfig(builder.build());
    return request;
}

From source file:cn.jachohx.crawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);
    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

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

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/* ww  w  .j av a  2 s  .  c om*/

    connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != 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);
    }

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

    });

}

From source file:com.msopentech.thali.utilities.universal.CreateClientBuilder.java

/**
 *
 * @param host//from  w  ww . j  a  va  2  s . c om
 * @param port
 * @param serverPublicKey If null then the server won't be validated
 * @return
 */
public HttpClient CreateApacheClient(String host, int port, PublicKey serverPublicKey, KeyStore clientKeyStore,
        char[] clientKeyStorePassPhrase, Proxy proxy)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    //  sslSocketFactory
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false); // Work around for bug in TJWS, it doesn't properly
                                                            // support ExpectContinue
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setTcpNoDelay(params, Boolean.TRUE);
    params.setParameter(ClientPNames.DEFAULT_HOST, new HttpHost(host, port, "https"));

    HttpKeyHttpClient httpKeyHttpClient = new HttpKeyHttpClient(serverPublicKey, clientKeyStore,
            clientKeyStorePassPhrase, proxy, params);
    return httpKeyHttpClient;
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

public void collect() {
    if (isPingCompat.get()) {
        // back compat w/ old url.availability templates
        super.collect();
        return;/*from   w w w  . j  a va2s .  c  om*/
    }
    this.matches.clear();
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert());
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    double avail = 0;
    try {
        if (getMethod().equals(HttpHead.METHOD_NAME)) {
            request = new HttpHead(getURL());
            addParams(request, this.params.get());
        } else if (getMethod().equals(HttpPost.METHOD_NAME)) {
            HttpPost httpPost = new HttpPost(getURL());
            request = httpPost;
            addParams(httpPost, this.params.get());
        } else {
            request = new HttpGet(getURL());
            addParams(request, this.params.get());
        }
        request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow());
        addCredentials(request, client);
        startTime();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        int tries = 0;
        while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) {
            tries++;
            Header header = response.getFirstHeader("Location");
            String url = header.getValue();
            String[] toks = url.split(";");
            String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0];
            response = getRedirect(toks[0], t.length > 1 ? t[1] : "");
            statusCode = response.getStatusLine().getStatusCode();
        }
        endTime();
        setResponseCode(statusCode);
        avail = getAvail(statusCode);
        StringBuilder msg = new StringBuilder(String.valueOf(statusCode));
        Header header = response.getFirstHeader("Server");
        msg.append(header != null ? " (" + header.getValue() + ")" : "");
        setLastModified(response, statusCode);
        avail = checkPattern(response, avail, msg);
        setAvailMsg(avail, msg);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding: " + e, e);
    } catch (IOException e) {
        avail = Metric.AVAIL_DOWN;
        setErrorMessage(e.toString());
    } finally {
        setAvailability(avail);
    }
    netstat();
}

From source file:com.zia.freshdocs.cmis.CMIS.java

public InputStream makeHttpRequest(boolean isPost, String path, String payLoad, String contentType) {
    try {/*from   w w w .j  av a  2  s . c om*/
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);
        params.setParameter("http.connection.timeout", new Integer(TIMEOUT));

        // registers schemes for both http and https
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), _prefs.getPort()));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), _prefs.getPort()));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);

        String url = new URL(_prefs.isSSL() ? "https" : "http", _prefs.getHostname(), buildRelativeURI(path))
                .toString();
        HttpClient client = new DefaultHttpClient(manager, params);
        client.getParams();
        _networkStatus = NetworkStatus.OK;

        HttpRequestBase request = null;

        if (isPost) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(payLoad));
        } else {
            request = new HttpGet(url);
        }

        try {

            if (contentType != null) {
                request.setHeader("Content-type", contentType);
            }

            HttpResponse response = client.execute(request);
            StatusLine status = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            int statusCode = status.getStatusCode();

            if ((statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) && entity != null) {
                // Just return the whole chunk
                return entity.getContent();
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                _networkStatus = NetworkStatus.CREDENTIALS_ERROR;
            }
        } catch (Exception ex) {
            Log.e(CMIS.class.getName(), "Get method error", ex);
            _networkStatus = NetworkStatus.CONNECTION_ERROR;
        }
    } catch (Exception ex) {
        Log.e(CMIS.class.getName(), "Get method error", ex);
        _networkStatus = NetworkStatus.UNKNOWN_ERROR;
    }

    return null;
}

From source file:com.chatsdk.kenai.jbosh.ApacheHTTPSender.java

private synchronized HttpClient initHttpClient(final BOSHClientConfig config) {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params, false);
    if (config != null && config.getProxyHost() != null && config.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }// ww w .ja va  2  s  .  co  m

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslFactory = SSLSocketFactory.getSocketFactory();
    sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("https", sslFactory, 443));

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

From source file:com.funambol.platform.HttpConnectionAdapter.java

public HttpConnectionAdapter() {

    // These default values are mostly grabbed from the AndroidDefaultClient
    // implementation that was introduced in Android 2.2
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    params.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    // 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.
    params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    //HttpConnectionParams.setSocketBufferSize(params, 8192);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, params);
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*from  ww w  . j  a va2 s .  c  o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}