zoukankan      html  css  js  c++  java
  • android http 和https请求

        private static final int CONNECTION_TIMEOUT = 10000;
    
        public static String doHttpGet(String serverURL) throws Exception {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpClient hc = new DefaultHttpClient();
            HttpGet get = new HttpGet(serverURL);
            get.addHeader("Content-Type", "text/xml");
            get.setParams(httpParameters);
            HttpResponse response = null;
            try {
                response = hc.execute(get);
            } catch (UnknownHostException e) {
                throw new Exception("Unable to access " + e.getLocalizedMessage());
            } catch (SocketException e) {
                throw new Exception(e.getLocalizedMessage());
            }
            int sCode = response.getStatusLine().getStatusCode();
            if (sCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else
                throw new Exception("StatusCode is " + sCode);
        }
    
        public static String doHttpsGet(String serverURL) throws Exception {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpClient hc = initHttpClient(httpParameters);
            HttpGet get = new HttpGet(serverURL);
            get.addHeader("Content-Type", "text/xml");
            get.setParams(httpParameters);
            HttpResponse response = null;
            try {
                response = hc.execute(get);
            } catch (UnknownHostException e) {
                throw new Exception("Unable to access " + e.getLocalizedMessage());
            } catch (SocketException e) {
                throw new Exception(e.getLocalizedMessage());
            }
            int sCode = response.getStatusLine().getStatusCode();
            if (sCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else
                throw new Exception("StatusCode is " + sCode);
        }
    
        public static String doHttpPost(String serverURL, String xmlString) throws Exception {
            Log.d("doHttpPost", "serverURL="+serverURL);
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
            HttpClient hc = new DefaultHttpClient();
            HttpPost post = new HttpPost(serverURL);
            post.addHeader("Content-Type", "text/xml");
            post.setEntity(new StringEntity(xmlString, "UTF-8"));
            post.setParams(httpParameters);
            HttpResponse response = null;
            try {
                response = hc.execute(post);
            } catch (UnknownHostException e) {
                throw new Exception("Unable to access " + e.getLocalizedMessage());
            } catch (SocketException e) {
                throw new Exception(e.getLocalizedMessage());
            }
            int sCode = response.getStatusLine().getStatusCode();
            Log.d("response code ", "sCode="+sCode);
            if (sCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else
                throw new Exception("StatusCode is " + sCode);
        }
    
        public static String doHttpsPost(String serverURL, String xmlString) throws Exception {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParameters, CONNECTION_TIMEOUT);
            HttpClient hc = initHttpClient(httpParameters);
            HttpPost post = new HttpPost(serverURL);
            post.addHeader("Content-Type", "text/xml");
            post.setEntity(new StringEntity(xmlString, "UTF-8"));
            post.setParams(httpParameters);
            HttpResponse response = null;
            try {
                response = hc.execute(post);
            } catch (UnknownHostException e) {
                throw new Exception("Unable to access " + e.getLocalizedMessage());
            } catch (SocketException e) {
                throw new Exception(e.getLocalizedMessage());
            }
            int sCode = response.getStatusLine().getStatusCode();
            if (sCode == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            } else
                throw new Exception("StatusCode is " + sCode);
        }
    
        public static HttpClient initHttpClient(HttpParams params) {
            try {
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null, null);
    
                SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);
                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
                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);
    
                return new DefaultHttpClient(ccm, params);
            } catch (Exception e) {
                return new DefaultHttpClient(params);
            }
        }
    
        public static class SSLSocketFactoryImp extends SSLSocketFactory {
            final SSLContext sslContext = SSLContext.getInstance("TLS");
    
            public SSLSocketFactoryImp(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();
            }
        }
  • 相关阅读:
    Python Day 30 网络编程 (串讲 FTP作业)
    Python Day 29 网络编程 ( socket中的一些常见方法,登录验证,socketserver模块)
    Python Day 28 网络编程 (socket远程命令执行, tcp黏包现象,以及struck模块的使用 )
    Python Day 27 网络编程 (socket udp)
    Python Day 26 网络编程 ( 网络编程基础 socket tcp)
    Python Day 25 蜥蜴串讲
    Python Day 24 面向对象进阶(双下方法 __new__ __del__ item系列 异常处理)
    Python Day 23 面向对象进阶(内置方法:反射,isinstance和issubclass,__str__和__repr__和其他双下方法)
    Python Day 21 面向对象 (面向对象的三大特性(二)继承,多态,封装,几个装饰器函数)
    aaencode:用颜文字来加密吧
  • 原文地址:https://www.cnblogs.com/zhuqiang/p/3623786.html
Copyright © 2011-2022 走看看