`
peirubing
  • 浏览: 32022 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

AndroidHttpClient

 
阅读更多

public final class AndroidHttpClient implements HttpClient
{

    // Gzip of data shorter than this probably won't be worthwhile
    public static long DEFAULT_SYNC_MIN_GZIP_BYTES = 256;

    private static final String TAG = "AndroidHttpClient";

    /**
     * TLS protocol
     */
    private static final String CLIENT_AGREEMENT = "TLS";

    /** Interceptor throws an exception if the executing thread is blocked */
    private static final HttpRequestInterceptor sThreadCheckInterceptor = new HttpRequestInterceptor()
    {
        public void process(HttpRequest request, HttpContext context)
        {
            // Prevent the HttpRequest from being sent on the main thread
            // if (Looper.myLooper() != null && Looper.myLooper() ==
            // Looper.getMainLooper() ) {
            // throw new RuntimeException("This thread forbids HTTP requests");
            // }
        }
    };

    private static 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;
        }
    };

    /**
     * Create a new HttpClient with reasonable defaults (which you can update).
     *
     * @param userAgent
     *            to report in your HTTP requests
     * @param context
     *            to use for caching SSL sessions (may be null for no caching)
     * @return AndroidHttpClient for you to use for all your requests.
     */
    public static AndroidHttpClient newInstance(String userAgent,
            Context context)
    {
        HttpParams params = new BasicHttpParams();

        // 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.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // Default connection and socket timeout of 20 seconds. Tweak to taste.
        HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
        HttpConnectionParams.setSoTimeout(params, 20 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        // Don't handle redirects -- return them to the caller. Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, false);

        // Use a session cache for SSL sockets
        SSLSessionCache sessionCache = context == null ? null
                : new SSLSessionCache(context);

        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, userAgent);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        try
        {
            KeyStore trustStore = KeyStore.getInstance(KeyStore
                    .getDefaultType());
            trustStore.load(null, null);
            SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", sf, 443));

            ClientConnectionManager manager = new ThreadSafeClientConnManager(
                    params, schemeRegistry);

            // We use a factory method to modify superclass initialization
            // parameters without the funny call-a-static-method dance.
            return new AndroidHttpClient(manager, params);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

    }

    /**
     * Create a new HttpClient with reasonable defaults (which you can update).
     *
     * @param userAgent
     *            to report in your HTTP requests.
     * @return AndroidHttpClient for you to use for all your requests.
     */
    public static AndroidHttpClient newInstance(String userAgent)
    {
        return newInstance(userAgent, null /* session cache */);
    }
}

 

 

 

public class SSLSocketFactoryEx extends SSLSocketFactory
{
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public SSLSocketFactoryEx(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, UnrecoverableKeyException
    {
        super(truststore);

        TrustManager tm = new X509TrustManager()
        {
            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }

            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException
            {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException
            {
            }
        };
        sslContext.init(null, new TrustManager[]
        {tm}, null);
    }
   
    @Override 
    public Socket createSocket(Socket socket, String host, int port,boolean autoClose) throws IOException, UnknownHostException { 
            return sslContext.getSocketFactory().createSocket(socket, host, port,autoClose); 
    } 
  
    @Override 
    public Socket createSocket() throws IOException { 
        return sslContext.getSocketFactory().createSocket(); 
    } 
}

分享到:
评论

相关推荐

    Android HttpClient工具类

    本篇文章将深入探讨Android HttpClient的基本使用方法,帮助开发者理解和应用这个工具。 首先,我们来了解HttpClient的核心组件: 1. **HttpClient实例**:这是所有操作的基础,通过`HttpClient client = new ...

    android httpClient所需jar包

    本主题聚焦于"android httpClient所需jar包"以及与之相关的ksoap2库,这些都是Android应用开发中不可或缺的部分。 首先,让我们详细了解这些jar包的作用: 1. **commons-httpclient-3.1.jar**: 这是Apache ...

    Android HttpClient用到的jar包

    本篇将详细讲解如何利用Apache HttpClient及其相关的jar包在Android环境中进行文件上传。 首先,我们关注的是标题提到的两个jar包:“apache-mime4j-0.6.jar”和“httpmime-4.0.jar”。这两个jar包是HttpClient库的...

    android httpclient demo

    然而,由于Android API Level 23之后不再支持HttpClient,开发者现在更多地转向使用OkHttp或Retrofit等现代网络库。尽管如此,对于旧项目或者对HttpClient有特定需求的场景,理解其工作原理和用法仍然很有价值。 1....

    android httpClient

    然而,从Android API 23(Marshmallow)开始,HttpClient被标记为废弃,推荐使用Android的HttpURLConnection或者其他的第三方库如OkHttp、Retrofit等。尽管如此,对于理解Android网络编程的基础和历史,HttpClient...

    Android HttpClient源码

    在这个"Android HttpClient源码"中,我们可以深入理解其内部工作原理,并学习如何在Android应用中有效地使用它。 首先,HttpClient的核心类是`HttpClient`,它是整个HTTP客户端操作的管理者。通过`HttpClient`,...

    Android Httpclient Proxy Test

    本文将深入探讨如何在Android中使用HttpClient进行代理设置,并结合具体的例子来阐述相关知识点。 首先,了解`HttpClient`是Apache的一个开源库,它提供了一个强大的、功能丰富的HTTP客户端API,使得开发者可以方便...

    android HttpClient

    在Android应用程序中,`HttpClient`经常被用于实现网络通信,比如上传或下载文件。下面将详细讨论`HttpClient`在Android中的应用及其相关知识点。 一、`HttpClient`基础 1. `HttpClient`类:它是整个框架的核心,...

    Android HttpClient与Json解析

    首先,我们需要了解如何使用Android的HttpClient。在Android SDK中,`org.apache.http.impl.client.DefaultHttpClient`是主要的HttpClient实现。创建一个HttpClient实例后,你可以通过`HttpGet`或`HttpPost`对象来...

    struts2 android httpclient 上传文件

    Struts2、Android和HttpClient是三个关键的技术领域,它们在本次文件上传的场景中相互结合。Struts2是一个流行的Java Web框架,用于构建MVC(模型-视图-控制器)结构的应用程序。Android是Google开发的移动操作系统...

    android httpclient

    android9.0不再支持useLibrary 'org.apache.http.legacy'引入httpclient,需要引入jar

    android HttpClient 获取网络图片

    android HttpClient 获取网络图片 实例

    AndroidHttpClient详解及调用示例

    创建AndroidHttpClient对象非常简单,只需调用`AndroidHttpClient.newInstance(String userAgent)`,其中userAgent参数通常为空字符串。如果不需要设置代理,可以留空。例如: ```java AndroidHttpClient client = ...

    Android HttpClient Network Lib

    总结来说,`Android HttpClient Network Lib`是一个关于如何在Android应用中使用HttpClient进行网络通信的知识点,涵盖了HttpClient的基本使用方法、优势,以及如何利用提供的jar包和源码进行开发。虽然HttpClient已...

    android HttpClient访问Https

    android HttpClient访问某些Https时,出现了问题,无法访问,好像是要安全验证。此Demo解决了此问题,HttpClient能够Https和Http类型的URL了。 在eclipse下打开工程若有乱码,请把eclipse的字符编码改成UTF-8。

    AndroidHttpClient访问Tomcat双向SSL验证服务器.pdf

    ### AndroidHttpClient访问Tomcat双向SSL验证服务器 #### 环境与背景介绍 本文主要讨论如何使用`AndroidHttpClient`访问`Tomcat`双向SSL验证服务器的相关技术和实施步骤。本项目的目标是在`Android WebView`上成功...

    Android httpclient httpmine4j

    然而,Android原生的HttpClient并不支持Multipart/form-data类型的请求,这在上传文件时是个问题。为了解决这个问题,我们可以引入第三方库如`httpclient`和`httpmime`,特别是`httpmine4j`相关的组件。 `...

    android httpclient4

    ### Android HttpClient4 使用详解 #### 一、概述 在Android应用开发中,网络通信是非常重要的一个环节。HttpClient作为Apache组织下的一个开源项目,为开发者提供了简单而强大的HTTP客户端功能。HttpClient 4.x...

    Android_HttpClient_jar包+HttpClientJarAndSource

    《Android HttpClient库详解与应用实践》 在移动开发领域,Android平台上的网络通信是一个至关重要的环节,HttpClient作为早期广泛使用的网络请求库,对于许多开发者来说并不陌生。本资源"Android_HttpClient_jar包...

    android HttpClient 上传图片

    在Android开发中,使用`HttpClient`进行图片上传是一项常见的需求,尤其在实现用户头像上传、照片分享等功能时。下面将详细解析如何利用`HttpClient`完成这一任务。 ### 使用`HttpClient`上传图片的关键步骤 #### ...

Global site tag (gtag.js) - Google Analytics