Android中的Https网络请求get和post

本文详细介绍了HTTPS的工作原理及其与HTTP的主要区别,并提供了Android平台上的HTTPS Get和Post请求的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer是通过证书认证、数据加密打造的一条安全的HTTP通道,也就是安全版HTTP,一般在金融行业用到的比较多。使用Https加密需要第三方机构进行认证,不然浏览器会提示证书不安全。当然也可以自制证书,像12306网站就是采用自制证书

Https的工作原理;

1、客户端向服务器发起Https请求;

2、服务器响应并下发证书,证书包含有公钥、证书颁发机构、过期时间、对称加密算法种类等信息;

3、客户端接收到证书后,解析证书信息验证是否合法;

4、证书合法客户端解析对称加密算法种类,并生成对应的密钥(对称加密)通过公钥加密给服务器;

5、后面服务器与客户端通讯就采用对称加密进行加解密,密钥只有客户端与服务器知道,只要加密算法够安全,数据就足够安全;


Https和Http的区别:

1、HTTP URL http:// 开头,而HTTPS URL https:// 开头

2、HTTP 是不安全的,而 HTTPS 是安全的

3、HTTP 无法加密,而HTTPS 对传输的数据进行加密

4、 HTTP无需证书,而HTTPS 需要CA机构wosign的颁发的SSL证书


Android中代码

Https Get请求

[java]  view plain  copy
  1. package com.test;  
  2.   
  3. import android.os.Handler;  
  4. import android.os.Message;  
  5. import android.util.Log;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.HttpStatus;  
  9. import org.apache.http.HttpVersion;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.methods.HttpGet;  
  12. import org.apache.http.conn.ClientConnectionManager;  
  13. import org.apache.http.conn.scheme.PlainSocketFactory;  
  14. import org.apache.http.conn.scheme.Scheme;  
  15. import org.apache.http.conn.scheme.SchemeRegistry;  
  16. import org.apache.http.conn.ssl.SSLSocketFactory;  
  17. import org.apache.http.impl.client.DefaultHttpClient;  
  18. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  19. import org.apache.http.params.BasicHttpParams;  
  20. import org.apache.http.params.HttpConnectionParams;  
  21. import org.apache.http.params.HttpParams;  
  22. import org.apache.http.params.HttpProtocolParams;  
  23. import org.apache.http.protocol.HTTP;  
  24. import org.apache.http.util.EntityUtils;  
  25.   
  26. import java.net.SocketException;  
  27. import java.net.UnknownHostException;  
  28. import java.security.KeyStore;  
  29.   
  30. /** 
  31.  * Https get请求 
  32.  */  
  33. public class HttpsGetThread extends Thread {  
  34.   
  35.     private Handler handler;  
  36.     private String httpUrl;  
  37.     private int mWhat;  
  38.   
  39.     // public static final int ERROR = 404;  
  40.     // public static final int SUCCESS = 200;  
  41.   
  42.     public HttpsGetThread(Handler handler, String httpUrl) {  
  43.         super();  
  44.         this.handler = handler;  
  45.         this.httpUrl = httpUrl;  
  46.         mWhat = 200;  
  47.     }  
  48.   
  49.     public HttpsGetThread(Handler handler, String httpUrl, int what) {  
  50.         super();  
  51.         this.handler = handler;  
  52.         this.httpUrl = httpUrl;  
  53.         mWhat = what;  
  54.     }  
  55.   
  56.     @Override  
  57.     public void run() {  
  58.         // TODO Auto-generated method stub  
  59.         try {  
  60.             HttpParams httpParameters = new BasicHttpParams();  
  61.             HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);  
  62.             HttpConnectionParams.setSoTimeout(httpParameters, 10000);  
  63.             HttpClient hc = getHttpClient(httpParameters);  
  64.             HttpGet get = new HttpGet(httpUrl);  
  65.             get.setParams(httpParameters);  
  66.             HttpResponse response = null;  
  67.             try {  
  68.                 response = hc.execute(get);  
  69.             } catch (UnknownHostException e) {  
  70.                 throw new Exception("Unable to access "  
  71.                         + e.getLocalizedMessage());  
  72.             } catch (SocketException e) {  
  73.                 throw new Exception(e.getLocalizedMessage());  
  74.             }  
  75.             int sCode = response.getStatusLine().getStatusCode();  
  76.             if (sCode == HttpStatus.SC_OK) {  
  77.                 String result = EntityUtils.toString(response.getEntity(),  
  78.                         HTTP.UTF_8);  
  79.                 handler.sendMessage(Message.obtain(handler, mWhat, result)); // 请求成功  
  80.                 Log.i("info""result = " + result);  
  81.             } else {  
  82.                 String result = EntityUtils.toString(response.getEntity(),  
  83.                         HTTP.UTF_8);  
  84.                 Log.i("info""result = " + result);  
  85.             }  
  86.   
  87.         } catch (Exception e) {  
  88.             e.printStackTrace();  
  89.             Log.i("info""=============异常退出==============");  
  90.             handler.sendMessage(Message.obtain(handler, 404"异常退出"));  
  91.         }  
  92.   
  93.         super.run();  
  94.     }  
  95.   
  96.     /** 
  97.      * 获取HttpClient 
  98.      *  
  99.      * @param params 
  100.      * @return 
  101.      */  
  102.     public static HttpClient getHttpClient(HttpParams params) {  
  103.         try {  
  104.             KeyStore trustStore = KeyStore.getInstance(KeyStore  
  105.                     .getDefaultType());  
  106.             trustStore.load(nullnull);  
  107.   
  108.             SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);  
  109.             sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  110.   
  111.             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  112.             HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
  113.             HttpProtocolParams.setUseExpectContinue(params, true);  
  114.   
  115.             // 设置http https支持  
  116.             SchemeRegistry registry = new SchemeRegistry();  
  117.             registry.register(new Scheme("http", PlainSocketFactory  
  118.                     .getSocketFactory(), 80));  
  119.             registry.register(new Scheme("https", sf, 443));// SSL/TSL的认证过程,端口为443  
  120.             ClientConnectionManager ccm = new ThreadSafeClientConnManager(  
  121.                     params, registry);  
  122.             return new DefaultHttpClient(ccm, params);  
  123.         } catch (Exception e) {  
  124.             return new DefaultHttpClient(params);  
  125.         }  
  126.     }  
  127. }  

Http Post请求

[java]  view plain  copy
  1. package com.test;  
  2.   
  3. import android.os.Handler;  
  4. import android.os.Message;  
  5.   
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.HttpStatus;  
  8. import org.apache.http.HttpVersion;  
  9. import org.apache.http.NameValuePair;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.conn.ClientConnectionManager;  
  14. import org.apache.http.conn.params.ConnManagerParams;  
  15. import org.apache.http.conn.scheme.PlainSocketFactory;  
  16. import org.apache.http.conn.scheme.Scheme;  
  17. import org.apache.http.conn.scheme.SchemeRegistry;  
  18. import org.apache.http.conn.ssl.SSLSocketFactory;  
  19. import org.apache.http.impl.client.DefaultHttpClient;  
  20. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  21. import org.apache.http.params.BasicHttpParams;  
  22. import org.apache.http.params.HttpConnectionParams;  
  23. import org.apache.http.params.HttpParams;  
  24. import org.apache.http.params.HttpProtocolParams;  
  25. import org.apache.http.protocol.HTTP;  
  26. import org.apache.http.util.EntityUtils;  
  27.   
  28. import java.net.SocketException;  
  29. import java.net.UnknownHostException;  
  30. import java.security.KeyStore;  
  31. import java.util.List;  
  32.   
  33. /** 
  34.  * Https Post请求 
  35.  */  
  36. public class HttpsPostThread extends Thread {  
  37.   
  38.     private Handler handler;  
  39.     private String httpUrl;  
  40.     private List<NameValuePair> valueList;  
  41.     private int mWhat;  
  42.   
  43.     public static final int ERROR = 404;  
  44.     public static final int SUCCESS = 200;  
  45.   
  46.     public HttpsPostThread(Handler handler, String httpUrl,  
  47.             List<NameValuePair> list, int what) {  
  48.         super();  
  49.         this.handler = handler;  
  50.         this.httpUrl = httpUrl;  
  51.         this.valueList = list;  
  52.         this.mWhat = what;  
  53.     }  
  54.   
  55.     public HttpsPostThread(Handler handler, String httpUrl,  
  56.             List<NameValuePair> list) {  
  57.         super();  
  58.         this.handler = handler;  
  59.         this.httpUrl = httpUrl;  
  60.         this.valueList = list;  
  61.         this.mWhat = SUCCESS;  
  62.     }  
  63.   
  64.     @Override  
  65.     public void run() {  
  66.         // TODO Auto-generated method stub  
  67.         String result = null;  
  68.         try {  
  69.             HttpParams httpParameters = new BasicHttpParams();  
  70.             // 设置连接管理器的超时  
  71.             ConnManagerParams.setTimeout(httpParameters, 10000);  
  72.             // 设置连接超时  
  73.             HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);  
  74.             // 设置socket超时  
  75.             HttpConnectionParams.setSoTimeout(httpParameters, 10000);  
  76.             HttpClient hc = getHttpClient(httpParameters);  
  77.             HttpPost post = new HttpPost(httpUrl);  
  78.             post.setEntity(new UrlEncodedFormEntity(valueList, HTTP.UTF_8));  
  79.             post.setParams(httpParameters);  
  80.             HttpResponse response = null;  
  81.             try {  
  82.                 response = hc.execute(post);  
  83.             } catch (UnknownHostException e) {  
  84.                 throw new Exception("Unable to access "  
  85.                         + e.getLocalizedMessage());  
  86.             } catch (SocketException e) {  
  87.                 throw new Exception(e.getLocalizedMessage());  
  88.             }  
  89.             int sCode = response.getStatusLine().getStatusCode();  
  90.             if (sCode == HttpStatus.SC_OK) {  
  91.                 result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);  
  92.                 if (handler != null) {  
  93.                     handler.sendMessage(Message.obtain(handler, mWhat, result)); // 请求成功  
  94.                 }  
  95.             } else {  
  96.                 result = "请求失败" + sCode; // 请求失败  
  97.                 // 404 - 未找到  
  98.                 if (handler != null) {  
  99.                     handler.sendMessage(Message.obtain(handler, ERROR, result));  
  100.                 }  
  101.             }  
  102.         } catch (Exception e) {  
  103.             e.printStackTrace();  
  104.             if (handler != null) {  
  105.                 result = "请求失败,异常退出";  
  106.                 handler.sendMessage(Message.obtain(handler, ERROR, result));  
  107.             }  
  108.         }  
  109.         super.run();  
  110.     }  
  111.   
  112.     /** 
  113.      * 获取HttpClient 
  114.      *  
  115.      * @param params 
  116.      * @return 
  117.      */  
  118.     public static HttpClient getHttpClient(HttpParams params) {  
  119.         try {  
  120.             KeyStore trustStore = KeyStore.getInstance(KeyStore  
  121.                     .getDefaultType());  
  122.             trustStore.load(nullnull);  
  123.   
  124.             SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);  
  125.             sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  126.   
  127.             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  128.             HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
  129.             HttpProtocolParams.setUseExpectContinue(params, true);  
  130.   
  131.             // 设置http https支持  
  132.             SchemeRegistry registry = new SchemeRegistry();  
  133.             registry.register(new Scheme("http", PlainSocketFactory  
  134.                     .getSocketFactory(), 80));  
  135.             registry.register(new Scheme("https", sf, 443));// SSL/TSL的认证过程,端口为443  
  136.             ClientConnectionManager ccm = new ThreadSafeClientConnManager(  
  137.                     params, registry);  
  138.             return new DefaultHttpClient(ccm, params);  
  139.         } catch (Exception e) {  
  140.             return new DefaultHttpClient(params);  
  141.         }  
  142.     }  
  143. }  

SSLSocketFactoryImp 类:

[java]  view plain  copy
  1. package com.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.Socket;  
  5. import java.net.UnknownHostException;  
  6. import java.security.KeyManagementException;  
  7. import java.security.KeyStore;  
  8. import java.security.KeyStoreException;  
  9. import java.security.NoSuchAlgorithmException;  
  10. import java.security.UnrecoverableKeyException;  
  11.   
  12. import javax.net.ssl.SSLContext;  
  13. import javax.net.ssl.TrustManager;  
  14. import javax.net.ssl.X509TrustManager;  
  15.   
  16. import org.apache.http.conn.ssl.SSLSocketFactory;  
  17.   
  18. public class SSLSocketFactoryImp extends SSLSocketFactory {  
  19.     final SSLContext sslContext = SSLContext.getInstance("TLS");  
  20.   
  21.     public SSLSocketFactoryImp(KeyStore truststore)  
  22.             throws NoSuchAlgorithmException, KeyManagementException,  
  23.             KeyStoreException, UnrecoverableKeyException {  
  24.         super(truststore);  
  25.   
  26.         TrustManager tm = new X509TrustManager() {  
  27.             public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
  28.                 return null;  
  29.             }  
  30.   
  31.             @Override  
  32.             public void checkClientTrusted(  
  33.                     java.security.cert.X509Certificate[] chain, String authType)  
  34.                     throws java.security.cert.CertificateException {  
  35.             }  
  36.   
  37.             @Override  
  38.             public void checkServerTrusted(  
  39.                     java.security.cert.X509Certificate[] chain, String authType)  
  40.                     throws java.security.cert.CertificateException {  
  41.             }  
  42.         };  
  43.   
  44.         sslContext.init(nullnew TrustManager[] { tm }, null);  
  45.     }  
  46.   
  47.     @Override  
  48.     public Socket createSocket(Socket socket, String host, int port,  
  49.             boolean autoClose) throws IOException, UnknownHostException {  
  50.         return sslContext.getSocketFactory().createSocket(socket, host, port,  
  51.                 autoClose);  
  52.     }  
  53.   
  54.     @Override  
  55.     public Socket createSocket() throws IOException {  
  56.         return sslContext.getSocketFactory().createSocket();  
  57.     }  
  58.   
  59. }  

测试类:

[java]  view plain  copy
  1. package com.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.os.Message;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10.   
  11. import org.apache.http.NameValuePair;  
  12. import org.apache.http.message.BasicNameValuePair;  
  13.   
  14. import java.util.ArrayList;  
  15. import java.util.List;  
  16.   
  17. public class MainActivity extends Activity {  
  18.     private Button btn, btn1;  
  19.     private Handler mHandler;  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         initView();  
  26.         initListener();  
  27.         initData();  
  28.   
  29.     }  
  30.   
  31.     private void initView() {  
  32.         btn = (Button) findViewById(R.id.btn);  
  33.         btn1 = (Button) findViewById(R.id.btn1);  
  34.     }  
  35.   
  36.     private void initListener() {  
  37.         btn.setOnClickListener(new View.OnClickListener() {  
  38.             @Override  
  39.             public void onClick(View v) {  
  40.                 List<NameValuePair> list = new ArrayList<NameValuePair>();  
  41.                 HttpsPostThread thread = new HttpsPostThread(mHandler,  
  42.                         "https://certs.cac.washington.edu/CAtest/", list, 200);  
  43.                 thread.start();  
  44.             }  
  45.         });  
  46.         btn1.setOnClickListener(new View.OnClickListener() {  
  47.             @Override  
  48.             public void onClick(View v) {  
  49.                 HttpsGetThread thread = new HttpsGetThread(mHandler,  
  50.                         "https://certs.cac.washington.edu/CAtest/"200);  
  51.                 thread.start();  
  52.             }  
  53.         });  
  54.     }  
  55.   
  56.     private void initData() {  
  57.         mHandler = new Handler() {  
  58.             @Override  
  59.             public void handleMessage(Message msg) {  
  60.                 super.handleMessage(msg);  
  61.                 String result = (String) msg.obj;  
  62.                 switch (msg.what) {  
  63.                 case 200:  
  64.                     // 请求成功  
  65.                     Log.e("TAG""返回参数===" + result);  
  66.                     break;  
  67.                 case 404:  
  68.                     // 请求失败  
  69.                     Log.e("TAG""请求失败!");  
  70.                     break;  
  71.                 }  
  72.   
  1.             }  
  2.         };  
  3.     }  


  4. 转载自:http://blog.youkuaiyun.com/lsf1025995457/article/details/51794377

  5.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值