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:jp.ne.sakura.kkkon.android.exceptionhandler.DefaultUploaderWeb.java

public static void upload(final Context context, final File file, final String url) {
    terminate();//w  w  w.j a  v a2  s  .  c o  m

    thread = new Thread(new Runnable() {

        @Override
        public void run() {
            Log.d(TAG, "upload thread tid=" + android.os.Process.myTid());
            try {
                //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                Log.d(TAG, "fng=" + Build.FINGERPRINT);
                final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                HttpPost httpPost = new HttpPost(url);
                //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                DefaultHttpClient httpClient = new DefaultHttpClient();
                Log.d(TAG, "socket.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                Log.d(TAG, "connection.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000));
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                        new Integer(5 * 1000));
                Log.d(TAG, "socket.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                Log.d(TAG, "connection.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                // <uses-permission android:name="android.permission.INTERNET"/>
                // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                HttpResponse response = httpClient.execute(httpPost);
                Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
            } catch (Exception e) {
                Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
            } finally {
                ExceptionHandler.clearReport();
            }
            Log.d(TAG, "upload finish");
        }
    });
    thread.setName("upload crash");

    thread.start();
    if (USE_DIALOG) {
        final AlertDialog.Builder alertDialogBuilder = setupAlertDialog(context);
        if (null != alertDialogBuilder) {
            alertDialogBuilder.setCancelable(false);

            final AlertDialog alertDialog = alertDialogBuilder.show();

            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            {
                try
                {
                    Thread.sleep( 1 * 1000 );
                }
                catch ( InterruptedException e )
                {
                    Log.d( TAG, "got exception", e );
                }
            }
                    
            if ( null != alertDialog )
            {
                if ( alertDialog.isShowing() )
                {
                }
                else
                {
                    if ( ! thread.isAlive() )
                    {
                        break;
                    }
                    alertDialog.show();
                }
            }
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
                    
            if ( null != alertDialog )
            {
            alertDialog.dismiss();
            }
            */
        }

        try {
            thread.join(); // must call. leak handle...
            thread = null;
        } catch (InterruptedException e) {
            Log.d(TAG, "got Exception", e);
        }
    }

}

From source file:com.emobc.android.utils.HttpUtils.java

/**
 * Take a client address is https by default if
 * @param https//from  ww w .  ja va 2 s  .c  o m
 * @return
 */
public static DefaultHttpClient getHttpClient(boolean https) {
    if (https) {
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        DefaultHttpClient client = new DefaultHttpClient();

        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("https", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

        // Set verifier      
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        return httpClient;
    }
    return new DefaultHttpClient();
}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

protected static DefaultHttpClient prepareHttpClient(URI uri, GHCredentials apiCredentials) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    httpClient.addRequestInterceptor(preemptiveAuth, 0);

    if (apiCredentials != null) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(apiCredentials.getUsername(), apiCredentials.getPassword()));
    }//from w ww  .jav a2s . c  om
    return httpClient;
}

From source file:org.sonar.ide.eclipse.wsclient.WSClientFactory.java

/**
 * Workaround for http://jira.codehaus.org/browse/SONAR-1586
 *//*  w w  w .  j a  va2s.  c o  m*/
private static void configureProxy(DefaultHttpClient httpClient, Host server) {
    try {
        IProxyData proxyData = getEclipseProxyFor(server);
        if (proxyData != null && !IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) {
            LOG.debug("Proxy for [{}] - [{}]", server.getHost(), proxyData);
            HttpHost proxy = new HttpHost(proxyData.getHost(), proxyData.getPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            if (proxyData.isRequiresAuthentication()) {
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(proxyData.getHost(), proxyData.getPort()),
                        new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword()));
            }
        } else {
            LOG.debug("No proxy for [{}]", server.getHost());
        }
    } catch (Exception e) {
        LOG.error("Unable to configure proxy for sonar-ws-client", e);
    }
}

From source file:messenger.YahooFinanceAPI.java

public static String httppost(String url, List<NameValuePair> header, String refer, boolean cookie) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (cookie)/*w  ww  .j  a  v  a  2s . co m*/
        httpclient.setCookieStore(cookiestore);
    else if (cookiestore1 != null)
        httpclient.setCookieStore(cookiestore1);
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    HttpPost httpPost = new HttpPost(url);
    httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    Header[] headers = { new BasicHeader("Accept",
            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"),
            new BasicHeader("Content-Type", "application/x-www-form-urlencoded"),
            new BasicHeader("Origin", "http://aomp.judicial.gov.tw"), new BasicHeader("Referer", refer),
            new BasicHeader("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.55 Safari/534.3") };

    httpPost.setHeaders(headers);

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(header, "Big5"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    HttpResponse response = null;
    String responseString = null;
    try {
        response = httpclient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (cookie)
                cookiestore = httpclient.getCookieStore();
            else
                cookiestore1 = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header[] urlh = response.getAllHeaders();
            System.out.println(urlh.toString());
        } else {
            System.out.println(response.getStatusLine());
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java

private static void configureProxy(final DefaultHttpClient httpClient, final RemoteStorageContext ctx) {
    final RemoteProxySettings rps = ctx.getRemoteProxySettings();

    if (rps.isEnabled()) {
        final HttpHost proxy = new HttpHost(rps.getHostname(), rps.getPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        // check if we have non-proxy hosts
        if (rps.getNonProxyHosts() != null && !rps.getNonProxyHosts().isEmpty()) {
            final Set<Pattern> nonProxyHostPatterns = new HashSet<Pattern>(rps.getNonProxyHosts().size());
            for (String nonProxyHostRegex : rps.getNonProxyHosts()) {
                try {
                    nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE));
                } catch (PatternSyntaxException e) {
                    logger.warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e);
                }/*  w  w  w. java2 s.  co m*/
            }
            httpClient.setRoutePlanner(new NonProxyHostsAwareHttpRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), nonProxyHostPatterns));
        }

        configureAuthentication(httpClient, rps.getHostname(), rps.getPort(), rps.getProxyAuthentication());
    }
}

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

private static HttpClient createHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectHandler(new RedirectHandler());
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    return httpClient;
}

From source file:uk.ac.diamond.scisoft.feedback.FeedbackRequest.java

/**
 * Method used to submit a form data/file through HTTP to a GAE servlet
 * /*from   www  . j a v  a  2s  . c om*/
 * @param email
 * @param to
 * @param name
 * @param subject
 * @param messageBody
 * @param attachmentFiles
 * @param monitor
 */
public static IStatus doRequest(String email, String to, String name, String subject, String messageBody,
        List<File> attachmentFiles, IProgressMonitor monitor) throws Exception {
    Status status = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    FeedbackProxy.init();
    host = FeedbackProxy.getHost();
    port = FeedbackProxy.getPort();

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    // if there is a proxy
    if (host != null) {
        HttpHost proxy = new HttpHost(host, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    try {
        HttpPost httpost = new HttpPost(SERVLET_URL + SERVLET_NAME);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("name", new StringBody(name));
        entity.addPart("email", new StringBody(email));
        entity.addPart("to", new StringBody(to));
        entity.addPart("subject", new StringBody(subject));
        entity.addPart("message", new StringBody(messageBody));

        // add attachement files to the multipart entity
        for (int i = 0; i < attachmentFiles.size(); i++) {
            if (attachmentFiles.get(i) != null && attachmentFiles.get(i).exists())
                entity.addPart("attachment" + i + ".html", new FileBody(attachmentFiles.get(i)));
        }

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        httpost.setEntity(entity);

        // HttpPost post = new HttpPost("http://dawnsci-feedback.appspot.com/dawnfeedback?name=baha&email=baha@email.com&subject=thisisasubject&message=thisisthemessage");
        HttpResponse response = httpclient.execute(httpost);

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        final String reasonPhrase = response.getStatusLine().getReasonPhrase();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            logger.debug("Status code 200");
            status = new Status(IStatus.OK, "Feedback successfully sent", "Thank you for your contribution");
        } else {
            logger.debug("Feedback email not sent - HTTP response: " + reasonPhrase);
            status = new Status(IStatus.WARNING, "Feedback not sent",
                    "The response from the server is the following:\n" + reasonPhrase
                            + "\nClick on OK to submit your feedback using the online feedback form available at http://dawnsci-feedback.appspot.com/");
        }
        logger.debug("HTTP Response: " + response.getStatusLine());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return status;
}

From source file:net.paissad.waqtsalat.service.utils.HttpUtils.java

private static HttpClient getNewHttpClient() throws WSException {

    try {/*  w w w  .j  av  a  2s . co  m*/
        TrustStrategy trustStrategy = new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        };
        SSLSocketFactory sf = new CustomSSLFactory(trustStrategy);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(sr);

        DefaultHttpClient client = new DefaultHttpClient(ccm);
        client.setHttpRequestRetryHandler(new CustomHttpRequestRetryHandler());
        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        List<String> authpref = new ArrayList<String>();
        // Choose BASIC over DIGEST for proxy authentication
        authpref.add(AuthPolicy.BASIC);
        authpref.add(AuthPolicy.DIGEST);
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);

        client.addRequestInterceptor(new CustomHttpRequestInterceptor());
        client.addResponseInterceptor(new CustomHttpResponseInterceptor());

        return client;

    } catch (Exception e) {
        throw new WSException("Error while creating a HTTP client.", e);
    }
}

From source file:test.Http.java

/**
 * post url :??jsonString???json,?json/*from   w  w w .  j  a  va 2  s .co m*/
 * 
 * @date
 * @param url
 * @param jsonString
 * @return
 * @throws Exception
 */
public static String httpPostWithJson(String url, String jsonString) {
    String result = "";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // 
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
    // ?
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
    HttpPost httpPost = new HttpPost(url);
    // ???
    try {
        StringEntity reqEntity = new StringEntity(jsonString, HTTP.UTF_8);
        httpPost.setHeader("Content-type", "text/xml; charset=utf-8");
        // ?
        httpPost.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(httpPost);// post
        HttpEntity entity = response.getEntity();
        // 
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        result = "";
        while ((line = reader.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}