Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:com.pangdata.sdk.http.AbstractHttp.java

protected boolean sendData(HttpRequestBase request) {
    logger.debug("Send data to server {}", fullurl);
    HttpResponse response = null;/*w  w  w .  j a v  a 2s.c  o  m*/
    HttpClient httpClient = httpClients.get(Thread.currentThread().getId());
    try {
        if (httpClient == null) {
            HttpParams myParams = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(myParams, 100000);
            HttpConnectionParams.setConnectionTimeout(myParams, 100000); // Timeout

            httpClient = SdkUtils.createHttpClient(url, myParams);

            httpClients.put(Thread.currentThread().getId(), httpClient);
            httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
        }

        if (!url.toLowerCase().startsWith("http")) {
            url = "http://" + url;
        }

        response = httpClient.execute(request);
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.error("HTTP error: {}", result);
            if (response.getStatusLine().getStatusCode() == 401) {
                logger.error("UNAUTHORIZED ERROR. Process will be shutdown. Verify your username and userkey");
                System.exit(1);
            }
            throw new IllegalStateException(String.format("HTTP error code : %s, Error message: %s",
                    response.getStatusLine().getStatusCode(), result));
        }

        logger.debug("Response: {}", result);

        Map<String, Object> responseMap = (Map<String, Object>) JsonUtils.toObject(result, Map.class);
        if (!(Boolean) responseMap.get("Success")) {
            throw new IllegalStateException(String.format("Error message: %s", responseMap.get("Message")));
        }
        return true;
    } catch (Exception e) {
        throw new PangException(e);
    }
}

From source file:com.zzl.zl_app.cache.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*from  w  w w  .  ja v a2s . 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();

        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);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??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:custom.application.login.java

public String oAuth2_github_callback() throws ApplicationException {
    HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST");
    HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE");
    Reforward reforward = new Reforward(request, response);

    if (this.getVariable("github_client_secrets") == null) {
        TextFileLoader loader = new TextFileLoader();
        loader.setInputStream(login.class.getResourceAsStream("/clients_secrets.json"));
        builder = new Builder();
        builder.parse(loader.getContent().toString());

        if (builder.get("github") instanceof Builder) {
            builder = (Builder) builder.get("github");

            System.out.println(builder.get("client_secret"));
            System.out.println(builder.get("client_id"));
            this.setVariable(new ObjectVariable("github_client_secrets", builder));
        }/* ww  w  .  j  a  v a2 s .  c  o  m*/
    } else
        builder = (Builder) this.getVariable("github_client_secrets").getValue();

    String arguments = this.http_client("https://github.com/login/oauth/access_token?client_id="
            + builder.get("client_id") + "&client_secret=" + builder.get("client_secret") + "&code="
            + request.getParameter("code"));

    try {

        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.github.com/user";

        HttpGet httpget = new HttpGet(url + "?" + arguments);
        httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

        HttpResponse http_response = httpClient.execute(httpget);
        HeaderIterator iterator = http_response.headerIterator();
        while (iterator.hasNext()) {
            Header next = iterator.nextHeader();
            System.out.println(next.getName() + ":" + next.getValue());
        }

        InputStream instream = http_response.getEntity().getContent();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];

        int len;
        while ((len = instream.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        instream.close();
        out.close();

        Struct struct = new Builder();
        struct.parse(new String(out.toByteArray(), "utf-8"));

        this.usr = new User();
        this.usr.setEmail(struct.toData().getFieldInfo("email").stringValue());

        if (this.usr.findOneByKey("email", this.usr.getEmail()).size() == 0) {
            usr.setPassword("");
            usr.setUsername(usr.getEmail());

            usr.setLastloginIP(request.getRemoteAddr());
            usr.setLastloginTime(new Date());
            usr.setRegistrationTime(new Date());
            usr.append();
        }

        new passport(request, response, "waslogined").setLoginAsUser(this.usr.getId());

        reforward.setDefault(URLDecoder.decode(this.getVariable("from").getValue().toString(), "utf8"));
        reforward.forward();

        return new String(out.toByteArray(), "utf-8");
    } catch (ClientProtocolException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new ApplicationException(e.getMessage(), e);
    }
}

From source file:ui.shared.FreebaseHelper.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base) {
    try {// w  ww.  j av  a  2 s .c om
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            public boolean verify(String string, SSLSession ssls) {
                return true;
            }

        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:wsattacker.http.transport.TlsWrapperClient.java

public static HttpClient wrapClient(HttpClient base) {
    try {//from www . j  a  va 2  s. c o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {
            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }

            @Override
            public void verify(String string, SSLSocket ssls) throws IOException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (NoSuchAlgorithmException ex) {
        return null;
    } catch (KeyManagementException ex) {
        return null;
    }
}

From source file:org.hupo.psi.mi.psicquic.ws.legacy.SolrBasedPsicquicRestService10.java

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

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(SolrBasedPsicquicService.maxTotalConnections);
    cm.setDefaultMaxPerRoute(SolrBasedPsicquicService.defaultMaxConnectionsPerHost);

    HttpClient httpClient = new DefaultHttpClient(cm);

    String proxyHost = config.getProxyHost();
    String proxyPort = config.getProxyPort();

    if (isValueSet(proxyHost) && proxyHost.trim().length() > 0 && isValueSet(proxyPort)
            && proxyPort.trim().length() > 0) {
        try {//w  w  w  .j a  v a  2s.co  m
            HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            logger.error("Impossible to create proxy host:" + proxyHost + ", port:" + proxyPort, e);
        }
    }

    return httpClient;
}

From source file:de.koczewski.maxapi.WebClientDevWrapper.java

public static DefaultHttpClient wrapClient(HttpClient base) {
    try {/* ww  w.  j  av a2s  .  co m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.wrmsr.neurosis.aws.client.WebClientDevWrapper.java

public static HttpClient wrapClient(HttpClient base) {
    try {//  ww w  .j a va 2s.  c o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:utils.httpUtil_inThread.java

/**
 * ?//ww w .  j  ava 2s  . com
 *
 * @return ?null
 */
public String HttpGetString(String website, String cookie, int timeout_connection, int timeout_read) {
    String result;
    try {
        String strHTTP = "http://";
        if (website != null && !website.contains(strHTTP))
            website = strHTTP + website; //?http://

        //1.?
        HttpClient client = new DefaultHttpClient();
        //2.?
        HttpGet httpGet = new HttpGet(website);

        if (cookie != null && !cookie.equals(""))
            httpGet.setHeader("Cookie", cookie);

        //??
        if (timeout_connection <= 1000)
            timeout_connection = timeout_text_connection;
        if (timeout_read < 1000)
            timeout_read = timeout_text_read;

        //HttpClient
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout_connection);
        //HttpClient?
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout_read);

        //3.??GET
        HttpResponse response = client.execute(httpGet);

        //4.??
        StringBuilder sb = new StringBuilder();
        HttpEntity entity = response.getEntity();

        //5.??
        String strEncoding = entity.getContentType().getValue();
        strEncoding = strEncoding.substring(strEncoding.indexOf("charset="));
        strEncoding = strEncoding.replace("charset=", "");

        //6.???
        int ResponseCode = response.getStatusLine().getStatusCode();
        if (ResponseCode == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), strEncoding));
            String temp;
            while ((temp = br.readLine()) != null) {
                String str = new String(temp.trim().getBytes());
                sb.append(str);
                sb.append("\r\n");
            }
            br.close();

            //???
            result = new String(sb);
        } else {
            //ResponseCode?200
            result = "";
            abstract_LogUtil.i(this, "[ResponseCode]" + ResponseCode);
        }
    } catch (Exception e) {
        result = "";
        abstract_LogUtil.e(this, "[?]" + website);
        abstract_LogUtil.e(this, "[GetHttp]" + e.toString());
    }
    return result;
}

From source file:org.jenkinsci.plugins.elasticsearchquery.ElasticsearchQueryBuilder.java

@Override
public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
        throws AbortException {
    //print our arguments
    listener.getLogger().println("Query: " + query);
    listener.getLogger().println("Fail when: " + aboveOrBelow);
    listener.getLogger().println("Threshold: " + threshold);
    listener.getLogger().println("Since: " + since);
    listener.getLogger().println("Time units: " + units);
    //get//from  www  .  j a v  a  2  s . c  o m
    final String user = getDescriptor().getUser();
    //get
    final String password = getDescriptor().getPassword();
    //validate global user and password config
    if (isEmpty(user) != isEmpty(password)) {
        throw new AbortException(
                "user and password must both be provided or empty! Please set value of user and password in Jenkins > Manage Jenkins > Configure System > Elasticsearch Query Builder");
    }

    final String creds = isEmpty(user) ? "" : user + ":" + password + "@";

    //get
    final String host = getDescriptor().getHost();
    //print
    listener.getLogger().println("host: " + host);
    //validate global host config
    if (isEmpty(host)) {
        throw new AbortException(
                "Host cannot be empty! Please set value of host in Jenkins > Manage Jenkins > Configure System > ElasticSearch Query Builder");
    }

    //Calculate time in past for search and indexes
    Long past = currentTimeMillis() - MILLISECONDS.convert(since, TimeUnit.valueOf(units));

    //create the date clause to be added the query to restrict by relative time
    final String dateClause = " AND @timestamp:>=" + past;
    //use past to calculate specific indexes to search similar to kibana 3
    //ie if we are looking back to yesterday we dont need to search every index 
    //only today and yesterday
    final String queryIndexes = isNotBlank(getDescriptor().getIndexes()) ? getDescriptor().getIndexes()
            : buildLogstashIndexes(past);
    listener.getLogger().println("queryIndexes: " + queryIndexes);

    //we have all the parts now build the query URL
    String url = null;
    try {
        url = "http" + (getDescriptor().getUseSSL() ? "s" : "") + "://" + creds + getDescriptor().getHost()
                + "/" + queryIndexes + "/_count?pretty=true&q=" + new URLCodec().encode(query + dateClause);
    } catch (EncoderException ee) {
        throw new RuntimeException(ee);
    }
    listener.getLogger().println("query url: " + url);

    HttpClient httpClient = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet(url);
    final Integer queryRequestTimeout = getDescriptor().getQueryRequestTimeout();
    setSoTimeout(httpClient.getParams(),
            queryRequestTimeout == null || queryRequestTimeout < 1
                    ? getDescriptor().defaultQueryRequestTimeout()
                    : queryRequestTimeout);
    HttpResponse response = null;

    try {
        response = httpClient.execute(httpget);
        listener.getLogger().println("response: " + response);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        String content = null;
        Long count = null;
        InputStream instream = null;
        try {

            instream = entity.getContent();

            // do something useful with the response
            content = IOUtils.toString(instream);
            listener.getLogger().println("content: " + content);
            Map<String, Object> map = new Gson().fromJson(content, new TypeToken<Map<String, Object>>() {
            }.getType());
            listener.getLogger().println("count: " + map.get("count"));
            count = Math.round((Double) map.get("count"));

        } catch (Exception ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            httpget.abort();
            throw new RuntimeException(ex);

        } finally {

            // Closing the input stream will trigger connection release
            closeQuietly(instream);

        }

        listener.getLogger().println("search url: " + replace(url, "_count", "_search"));

        final String abortMessage = threshold + ". Failing build!\n" + "URL: " + url + "\n"
                + "response content: " + content;
        if (aboveOrBelow.equals("gte")) {
            if (count >= threshold) {
                throw new AbortException("Count: " + count + " is >= " + abortMessage);
            }
        } else {
            if (count <= threshold) {
                throw new AbortException("Count: " + count + " is <= " + abortMessage);
            }
        }
    }
}