Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

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

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * Sets a timeout in milliseconds for retrieving of data (when 0 there is no timeout).
 *
 * @deprecated Replaced by {@link HttpClient#setTimeout(Object[])}.
 * /*from  w  w  w.ja  v a2  s . c o  m*/
 * @sample
 * plugins.http.setTimeout(1000,'client_name')
 *
 * @param msTimeout 
 * @param http_clientname optional
 */
@Deprecated
public void js_setTimeout(Object[] args) {
    if (args == null || args.length == 0 || args.length > 2)
        return;
    int timeout = Utils.getAsInteger(args[0], true);
    String name = args.length == 2 ? (String) args[1] : null;
    if (name == null) {
        this.timeout = timeout;
    } else {
        DefaultHttpClient client = getOrCreateHTTPclient(name, null);
        if (client != null) {
            HttpParams params = client.getParams();
            HttpConnectionParams.setConnectionTimeout(params, timeout);
            HttpConnectionParams.setSoTimeout(params, timeout);
        }
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

private DefaultHttpClient getOrCreateHTTPclient(String name, String url) {
    DefaultHttpClient client = httpClients.get(name);
    if (client == null) {
        client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

        if (name != null) {
            httpClients.put(name, client);
        }/*ww w  .j a v  a2  s  . c o  m*/
        if (url != null) {
            setHttpClientProxy(client, url, proxyUser, proxyPassword);
        }
    }
    return client;
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * /*from   w  w  w  .ja  va2 s.c  o m*/
 * @param request
 * @param cookie
 * @return The response of the request.
 * @throws WebserverSystemException
 */
private HttpResponse executeRequest(final DefaultHttpClient client, final HttpRequestBase request,
        final URL url, final Cookie cookie, final String username, final String password)
        throws WebserverSystemException {
    try {
        request.setURI(url.toURI());

        if (cookie != null) {
            HttpClientParams.setCookiePolicy(request.getParams(), CookiePolicy.BEST_MATCH);
            request.setHeader("Cookie", cookie.getName() + '=' + cookie.getValue());
        }

        final DefaultHttpClient clientToUse = client == null ? getHttpClient() : client;

        if (PROXY_HOST != null && isProxyRequired(url)) {
            clientToUse.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, PROXY_HOST);
        }

        if (username != null && password != null) {
            setAuthentication(clientToUse, url, username, password);
        }

        final HttpResponse httpResponse = clientToUse.execute(request);

        final int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode / HTTP_RESPONSE_CLASS != HttpServletResponse.SC_OK / HTTP_RESPONSE_CLASS) {
            final String errorPage = readResponse(httpResponse);
            throw new WebserverSystemException(
                    "HTTP connection to \"" + request.getURI().toString() + "\" failed: " + errorPage);
        }

        return httpResponse;
    } catch (final IOException e) {
        throw new WebserverSystemException(e);
    } catch (final URISyntaxException e) {
        throw new WebserverSystemException("Illegal URL '" + url + "'.", e);
    }
}

From source file:com.ibm.sbt.services.util.SSLUtil.java

public static DefaultHttpClient wrapHttpClient(DefaultHttpClient base) {
    try {/*from   w w  w . j av  a2  s.co m*/
        // Create and assign a dummy TrustManager
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);

        // When Apache Client AllowAllHostnameVerifier is strict, this should be used
        // Stays here for reference
        X509HostnameVerifier verifier = new X509HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }

            @Override
            public void verify(String s, SSLSocket sslSession) throws IOException {
            }

            @Override
            public void verify(String s, String[] ss1, String[] ss2) throws SSLException {
            }

            @Override
            public void verify(String s, X509Certificate cerst) throws SSLException {
            }

        };
        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:de.mprengemann.hwr.timetabel.data.Parser.java

protected Void doInBackground(Void... params) {
    this.exception = null;

    if (Utils.connectionChecker(context)) {
        try {//w  ww  . ja va  2  s  .  c  om
            final String matrikelnr = preferences.getString(context.getString(R.string.prefs_matrikelNrKey),
                    "");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            if (preferences.getBoolean(context.getString(R.string.prefs_proxyFlagKey), false)) {
                HttpHost proxy = new HttpHost(
                        preferences.getString(context.getString(R.string.prefs_proxyKey), "localhost"),
                        Integer.parseInt(
                                preferences.getString(context.getString(R.string.prefs_proxyPortKey), "8080")));
                httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }

            HttpGet httpget = new HttpGet(Utils.buildURL(context, preferences));

            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                entity.consumeContent();
            }

            List<Cookie> cookies = httpclient.getCookieStore().getCookies();

            HttpPost httpost = new HttpPost("http://ipool.ba-berlin.de/main.php?action=login");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("FORM_LOGIN_NAME", "student"));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_PASS", matrikelnr));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_PAGE", "home"));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_REDIRECTION", Utils.buildURL(context, preferences)));
            nvps.add(new BasicNameValuePair("FORM_ACCEPT", "1"));
            nvps.add(new BasicNameValuePair("LOGIN", "login"));

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

            response = httpclient.execute(httpost);
            entity = response.getEntity();

            if (entity != null) {
                entity.consumeContent();
            }

            cookies = httpclient.getCookieStore().getCookies();

            final URL url;
            InputStream is = null;
            try {
                url = new URL(Utils.buildURL(context, preferences));
                URLConnection c = url.openConnection();

                try {
                    c.setRequestProperty("Cookie", cookies.get(0).getName() + "=" + cookies.get(0).getValue());
                    c.connect();
                    is = c.getInputStream();
                } catch (NullPointerException e) {
                    throw new ConnectionAuthentificationException(
                            context.getString(R.string.dialog_error_message_auth));
                } catch (IndexOutOfBoundsException e) {
                    throw new ConnectionAuthentificationException(
                            context.getString(R.string.dialog_error_message_auth));
                }

                if (is != null) {
                    try {
                        new IcsParser(is, new OnCalendarParsingListener() {

                            @Override
                            public void onNewItem(Component c) {
                                if (c.getName().equals(Component.VEVENT)) {
                                    PropertyList p = c.getProperties();

                                    Subjects s = new Subjects();
                                    s.setTitle(p.getProperty("SUMMARY").getValue());
                                    s.setShortTitle(s.getTitle().substring(s.getTitle().indexOf("-") + 1));
                                    s.setShow(true);

                                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");

                                    Events evt = new Events();
                                    try {
                                        evt.setStart(df
                                                .parse(p.getProperty("DTSTART").getValue().replace("T", " ")));
                                        evt.setEnd(
                                                df.parse(p.getProperty("DTEND").getValue().replace("T", " ")));
                                    } catch (ParseException e) {
                                        exception = new IPoolFormatException(
                                                context.getString(R.string.dialog_error_message_ipool));
                                        sendBugReport(e, url.toString());
                                    }

                                    evt.setRoom(p.getProperty("LOCATION").getValue());
                                    evt.setUid(p.getProperty("UID").getValue());

                                    String description = p.getProperty("DESCRIPTION").getValue();
                                    evt.setFullDescription(description);
                                    for (String desc : description.split("\\n")) {
                                        if (desc.startsWith("Dozent: ")) {
                                            evt.setLecturer(desc.replace("Dozent: ", ""));
                                            break;
                                        } else if (desc.startsWith("Art: ")) {
                                            evt.setType(desc.replace("Art: ", ""));
                                        }
                                    }
                                    try {
                                        if (listener != null) {
                                            listener.onNewItem(s, evt);
                                        }
                                    } catch (SQLiteConstraintException e) {
                                        exception = new StorageException(
                                                context.getString(R.string.dialog_error_message_storage));
                                        sendBugReport(e, url.toString(), s.toString(), evt.toString());
                                    }

                                }
                            }
                        });
                    } catch (ParserException e) {
                        exception = new UnknownTimetableException(
                                context.getString(R.string.dialog_error_message_auth));
                        sendNewTimetable(url);
                    } catch (IOException e) {
                        if (e instanceof HttpHostConnectException) {
                            exception = new ConnectionTimeoutException(
                                    context.getString(R.string.dialog_error_message_timeout));
                        } else {
                            exception = new ConnectionException(
                                    context.getString(R.string.dialog_error_message));
                        }
                    }
                } else {
                    throw new IOException();
                }
            } catch (ConnectionAuthentificationException e) {
                exception = e;
            } catch (IOException e) {
                if (e instanceof ConnectTimeoutException) {
                    exception = new ConnectionTimeoutException(
                            context.getString(R.string.dialog_error_message_timeout));
                } else if (e instanceof MalformedURLException) {
                    exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                    sendBugReport(e);
                } else if (e instanceof HttpHostConnectException) {
                    exception = new ConnectionTimeoutException(
                            context.getString(R.string.dialog_error_message_timeout));
                } else {
                    exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                    sendBugReport(e);
                }
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    if (e instanceof ConnectTimeoutException) {
                        exception = new ConnectionTimeoutException(
                                context.getString(R.string.dialog_error_message_timeout));
                    } else {
                        exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                        sendBugReport(e);
                    }
                }
            }

            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                exception = new ConnectionTimeoutException(
                        context.getString(R.string.dialog_error_message_timeout));
            } else {
                exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                sendBugReport(e);
            }

        }
    } else {
        exception = new ConnectionException(context.getString(R.string.dialog_error_message));
    }

    return null;
}

From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java

private static void addProxyConfig(DefaultHttpClient httpClient) {
    Properties prop = System.getProperties();
    String proxyHost = prop.getProperty("http.proxyHost");
    Integer proxyPort = null;//from w  ww  .  jav  a  2 s. c o  m
    if (prop.getProperty("http.proxyPort") != null) {
        proxyPort = Integer.parseInt(prop.getProperty("http.proxyPort"));
    }
    String proxyUserName = prop.getProperty("http.proxyUser");
    String proxyPassword = prop.getProperty("http.proxyPassword");
    String proxyDomain = prop.getProperty("http.proxyDomain");
    if (proxy != null) {
        proxyHost = proxy.getProxyHost();
        proxyPort = proxy.getProxyPort();
        proxyUserName = proxy.getProxyUsername();
        proxyPassword = proxy.getProxyPassword();
        proxyDomain = proxy.getProxyDomainname();
    }

    if (proxyHost != null && proxyPort > 0) {
        Logger.debug(String.format("Using the proxy, proxyHost %s and proxyPort %d", proxyHost, proxyPort));

        HttpHost proxyServer = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer);

        if (proxyUserName != null && proxyUserName.trim().length() > 0 && proxyPassword != null
                && proxyPassword.length() > 0) {
            Logger.debug("Proxy Username:" + proxyUserName);
            Logger.debug("Proxy Domain:" + proxyDomain);

            AuthScope authScope = new AuthScope(proxyHost, proxyPort, null);
            NTCredentials credentials = new NTCredentials(proxyUserName, proxyPassword, "", proxyDomain);

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

            // Set NTLM authentication
            List<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthPolicy.NTLM);
            httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPrefs);
        }
    }
}

From source file:fr.eolya.utils.http.HttpLoader.java

private static HttpClient setProxy(DefaultHttpClient httpClient, String url, String proxyHost, String proxyPort,
        String proxyExclude, String proxyUser, String proxyPassword) {

    boolean exclude = false;

    if (StringUtils.isNotEmpty(proxyExclude)) {
        String[] aProxyExclude = proxyExclude.split(",");
        for (int i = 0; i < aProxyExclude.length; i++)
            aProxyExclude[i] = aProxyExclude[i].trim();

        try {//  ww  w.j  av  a 2  s  . c o m
            URL u = new URL(url);
            if (Arrays.asList(aProxyExclude).contains(u.getHost())) {
                exclude = true;
            }
        } catch (MalformedURLException e) {
            exclude = true;
        }
    }

    if (!exclude && StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)) {
        if (StringUtils.isNotEmpty(proxyUser) && StringUtils.isNotEmpty(proxyPassword)) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
        HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
    }
    return httpClient;
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Sets the proxy authentification for the client*/
private void setProxyToConnection(DefaultHttpClient client, AS2Message message, ProxyObject proxy) {
    //is a proxy requested?
    if (proxy.getHost() == null) {
        return;/* w  w w .j  a v  a2 s .c  om*/
    }
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), "http");
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
    if (proxy.getUser() != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxy.getHost(), proxy.getPort()),
                new UsernamePasswordCredentials(proxy.getUser(), String.valueOf(proxy.getPassword())));
        client.setCredentialsProvider(credsProvider);
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO, this.rb.getResourceString("using.proxy", new Object[] {
                message.getAS2Info().getMessageId(), proxy.getHost(), String.valueOf(proxy.getPort()), }),
                message.getAS2Info());
    }
}

From source file:com.juick.android.Utils.java

public static RESTResponse getJSON(final Context context, final String url,
        final Notification progressNotification, final int timeout, final boolean forceAttachCredentials) {
    final URLAuth authorizer = getAuthorizer(url);
    final RESTResponse[] ret = new RESTResponse[] { null };
    final URLAuth finalAuthorizer = authorizer;
    final boolean[] cookieCleared = { false };
    authorizer.authorize(context, false, forceAttachCredentials, url, new Function<Void, String>() {
        @Override//w  w  w.  jav a 2 s .  co  m
        public Void apply(String myCookie) {
            final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH);
            if (noAuthRequested)
                myCookie = null;
            final DefaultHttpClient client = getNewHttpClient();
            try {
                final Function<Void, String> thiz = this;
                final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
                boolean compression = sp.getBoolean("http_compression", false);
                long l = System.currentTimeMillis();
                if (compression)
                    initCompressionSupport(client);
                HttpGet httpGet = new HttpGet(authorizer.authorizeURL(url, myCookie));
                Integer timeoutForConnection = timeout > 0 ? timeout
                        : (sp.getBoolean("use_timeouts_json", false) ? 10000 : 2222000);
                client.getParams().setParameter("http.connection.timeout", timeoutForConnection);
                httpGet.getParams().setParameter("http.socket.timeout", timeoutForConnection);
                httpGet.getParams().setParameter("http.protocol.head-body-timeout", timeoutForConnection);

                finalAuthorizer.authorizeRequest(httpGet, myCookie);

                client.execute(httpGet, new ResponseHandler<Object>() {
                    @Override
                    public Object handleResponse(HttpResponse o) throws ClientProtocolException, IOException {
                        URLAuth.ReplyCode authReplyCode = o.getStatusLine().getStatusCode() == 200
                                ? URLAuth.ReplyCode.NORMAL
                                : authorizer.validateNon200Reply(o, url, forceAttachCredentials);
                        boolean simulateError = false;
                        if (o.getStatusLine().getStatusCode() == 200 && !simulateError) {
                            reloginTried = 0;
                            HttpEntity e = o.getEntity();
                            if (progressNotification instanceof DownloadProgressNotification) {
                                ((DownloadProgressNotification) progressNotification).notifyDownloadProgress(0);
                            }
                            InputStream content = e.getContent();
                            RESTResponse retval = streamToString(content, progressNotification);
                            content.close();
                            if (authorizer.isNoAuthInResponse(retval) && !cookieCleared[0]) {
                                cookieCleared[0] = true; // don't enter loop
                                authorizer.clearCookie(context, new Runnable() {
                                    @Override
                                    public void run() {
                                        authorizer.authorize(context, true, false, url, thiz);
                                    }
                                });
                                return null;
                            }
                            ret[0] = retval;
                        } else {
                            if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) {
                                ret[0] = new RESTResponse(NO_AUTH, false, null);
                                return o;
                            }
                            if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !forceAttachCredentials) {
                                ret[0] = getJSON(context, url, progressNotification, timeout, true);
                                return o;
                            } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) {
                                cookieCleared[0] = true; // don't enter loop
                                authorizer.clearCookie(context, new Runnable() {
                                    @Override
                                    public void run() {
                                        authorizer.authorize(context, true, false, url, thiz);
                                    }
                                });
                                return null;
                            } else if (o.getStatusLine().getStatusCode() / 100 == 4) {
                                if (context instanceof Activity) {
                                    final Activity activity = (Activity) context;
                                    reloginTried++;
                                    if (reloginTried == 3) {
                                        activity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                sp.edit().remove("web_cookie").commit();
                                                reloginTried = 0;
                                            }
                                        });
                                    }
                                }
                                // fall through
                            }

                            if (progressNotification instanceof DownloadErrorNotification) {
                                ((DownloadErrorNotification) progressNotification).notifyDownloadError(
                                        "HTTP response code: " + o.getStatusLine().getStatusCode());
                            }
                            ret[0] = new RESTResponse("HTTP: " + o.getStatusLine().getStatusCode() + " "
                                    + o.getStatusLine().getReasonPhrase(), false, null);
                        }
                        return o;
                    }
                });
                l = System.currentTimeMillis() - l;
                if (reportTimes) {
                    Toast.makeText(context, "Load time=" + l + " msec", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                if (progressNotification instanceof DownloadErrorNotification) {
                    ((DownloadErrorNotification) progressNotification)
                            .notifyDownloadError("HTTP connect: " + e.toString());
                }
                Log.e("getJSON", e.toString());
                ret[0] = new RESTResponse(e.toString(), true, null);
            } finally {
                client.getConnectionManager().shutdown();
            }
            return null; //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    while (ret[0] == null) { // bad, but true
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    return ret[0];
}