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(); 
    } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值