您的位置:首页 > 理论基础 > 计算机网络

Android中的Https网络请求get和post 不进行认证

2016-06-30 23:56 671 查看
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请求

package com.test;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.KeyStore;

/**
* Https get请求
*/
public class HttpsGetThread extends Thread {

private Handler handler;
private String httpUrl;
private int mWhat;

// public static final int ERROR = 404;
// public static final int SUCCESS = 200;

public HttpsGetThread(Handler handler, String httpUrl) {
super();
this.handler = handler;
this.httpUrl = httpUrl;
mWhat = 200;
}

public HttpsGetThread(Handler handler, String httpUrl, int what) {
super();
this.handler = handler;
this.httpUrl = httpUrl;
mWhat = what;
}

@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient hc = getHttpClient(httpParameters);
HttpGet get = new HttpGet(httpUrl);
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) {
String result = EntityUtils.toString(response.getEntity(),
HTTP.UTF_8);
handler.sendMessage(Message.obtain(handler, mWhat, result)); // 请求成功
Log.i("info", "result = " + result);
} else {
String result = EntityUtils.toString(response.getEntity(),
HTTP.UTF_8);
Log.i("info", "result = " + result);
}

} catch (Exception e) {
e.printStackTrace();
Log.i("info", "=============异常退出==============");
handler.sendMessage(Message.obtain(handler, 404, "异常退出"));
}

super.run();
}

/**
* 获取HttpClient
*
* @param params
* @return
*/
public static HttpClient getHttpClient(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);
HttpProtocolParams.setUseExpectContinue(params, true);

// 设置http https支持
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));// SSL/TSL的认证过程,端口为443
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient(params);
}
}
}

Http Post请求

package com.test;

import android.os.Handler;
import android.os.Message;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.util.List;

/**
* Https Post请求
*/
public class HttpsPostThread extends Thread {

private Handler handler;
private String httpUrl;
private List<NameValuePair> valueList;
private int mWhat;

public static final int ERROR = 404;
public static final int SUCCESS = 200;

public HttpsPostThread(Handler handler, String httpUrl,
List<NameValuePair> list, int what) {
super();
this.handler = handler;
this.httpUrl = httpUrl;
this.valueList = list;
this.mWhat = what;
}

public HttpsPostThread(Handler handler, String httpUrl,
List<NameValuePair> list) {
super();
this.handler = handler;
this.httpUrl = httpUrl;
this.valueList = list;
this.mWhat = SUCCESS;
}

@Override
public void run() {
// TODO Auto-generated method stub
String result = null;
try {
HttpParams httpParameters = new BasicHttpParams();
// 设置连接管理器的超时
ConnManagerParams.setTimeout(httpParameters, 10000);
// 设置连接超时
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
// 设置socket超时
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient hc = getHttpClient(httpParameters);
HttpPost post = new HttpPost(httpUrl);
post.setEntity(new UrlEncodedFormEntity(valueList, HTTP.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) {
result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
if (handler != null) {
handler.sendMessage(Message.obtain(handler, mWhat, result)); // 请求成功
}
} else {
result = "请求失败" + sCode; // 请求失败
// 404 - 未找到
if (handler != null) {
handler.sendMessage(Message.obtain(handler, ERROR, result));
}
}
} catch (Exception e) {
e.printStackTrace();
if (handler != null) {
result = "请求失败,异常退出";
handler.sendMessage(Message.obtain(handler, ERROR, result));
}
}
super.run();
}

/**
* 获取HttpClient
*
* @param params
* @return
*/
public static HttpClient getHttpClient(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);
HttpProtocolParams.setUseExpectContinue(params, true);

// 设置http https支持
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));// SSL/TSL的认证过程,端口为443
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient(params);
}
}
}

SSLSocketFactoryImp类:

如果要进行证书认证,可以在该方法中实现

package com.test;

import java.io.IOException;
import java.net.Socket;
import java.net.Unk
b100
nownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

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

}


测试类:

package com.test;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
private Button btn, btn1;
private Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initListener();
initData();

}

private void initView() {
btn = (Button) findViewById(R.id.btn);
btn1 = (Button) findViewById(R.id.btn1);
}

private void initListener() {
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
HttpsPostThread thread = new HttpsPostThread(mHandler,
"https://certs.cac.washington.edu/CAtest/", list, 200);
thread.start();
}
});
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpsGetThread thread = new HttpsGetThread(mHandler,
"https://certs.cac.washington.edu/CAtest/", 200);
thread.start();
}
});
}

private void initData() {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String result = (String) msg.obj;
switch (msg.what) {
case 200:
// 请求成功
Log.e("TAG", "返回参数===" + result);
break;
case 404:
// 请求失败
Log.e("TAG", "请求失败!");
break;
}

}
};
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息