public class HttpGetTools implements HttpTools {
private static final String TAG = "HttpGetTools";
/**
* 连接超时时间,毫秒
*/
private static final int TIME_OUT = 60000;
/**
* 网络通信缓存大小
*/
private static final int HTTP_CACHE = 1024 * 100;
private boolean mFinish;
protected HttpOnConnectionListener hol;
/**
* 网络连接超时时间
*/
private int mTimeout = TIME_OUT;
private HTTPSParams httpsParams;
public HttpGetTools(){
httpsParams = new HTTPSParams();
}
/**
* 获取HTTPS安全连接参数配置
* @return
*/
public HTTPSParams getHTTPSParams(){
return httpsParams;
}
/**
* 设置网络连接监听器
* @param listener
*/
protected void setConnectionListener(HttpOnConnectionListener listener){
this.hol = listener;
}
/**
* 获取数据
* @param urlPath 目标URL地址
* @return 发生异常返回null
*/
protected byte[] getData(String urlPath) {
if(mFinish){
throw new HttpToolsException("Connection has been terminated!");
}
HttpURLConnection http = null;
try{
URL url = new URL(urlPath);
byte[] cache = new byte[HTTP_CACHE];
http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(mTimeout);
http.setReadTimeout(mTimeout);
http.setRequestMethod("GET");
http.setRequestProperty("Charset", HTTP.UTF_8);
http.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
try{
if (http instanceof HttpsURLConnection) {
((HttpsURLConnection) http).setSSLSocketFactory(httpsParams.getSslSocketFactory() == null ?
getDefaultSSLSocketFactory() : httpsParams.getSslSocketFactory());
// Allow all hostnames
((HttpsURLConnection) http).setHostnameVerifier(httpsParams.getHostnameVerifier() == null ?
getDefaultHostnameVerifier() : httpsParams.getHostnameVerifier());
}
}catch(Exception e){
Log.e(TAG, e.toString());
}
http.connect();
final int code = http.getResponseCode();
if(code == HttpStatus.SC_OK){
Log.i(TAG, "the http resposed");
if(hol != null){
hol.onResponseOK();
}
InputStream inStream = http.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len = inStream.read(cache)) > 0) {
bos.write(cache, 0, len);
// Log.i("mFinish_len_in", ">>>>>>SSSS"+mFinish);
if(mFinish){
if(hol != null){
hol.onDisconnected();
// Log.i("mFinish_len", ">>>>>>"+mFinish);
}
return null;
}
}
bos.close();
byte[] compressData = bos.toByteArray();
if(hol != null){
if(!mFinish){
hol.onSuccessd(compressData);
}else{
hol.onDisconnected();
// Log.i("mFinish_len_down", ">>>>>>"+mFinish);
}
}
inStream.close();
return compressData;
}else{
if(hol != null && !mFinish){
hol.onResponseFailed(code);
}
}
}catch (Exception e) {
Log.e(TAG, e.toString());
if(hol != null && !mFinish){
hol.onError(e);
}
}finally{
if(http != null){
http.disconnect();
}
}
return null;
}
private SSLSocketFactory getDefaultSSLSocketFactory() throws Exception {
// Trust all certificates
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] TRUST_MANAGER = { new DefaultX509TrustManager() };
context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
SSLSocketFactory socketFactory = context.getSocketFactory();
return socketFactory;
}
private HostnameVerifier getDefaultHostnameVerifier(){
return new AllowAllHostnameVerifier();
}
/**
* 本方法用于使用get方法获取数据, 参数中的Object对象可以为空,无影响
*/
@Override
public byte[] postGetData(final String urlPath, Object part) {
return getData(urlPath);
}
/**
* 暂未实现该方法
*/
@Override
public byte[] uploadMultiPartData(String url, Map<String, String> requestData, Map<String,File> files) {
// TODO Auto-generated method stub
return null;
}
/**
* 暂未实现该方法
*/
@Override
public byte[] uploadMultiPartData(String url,
Map<String, String> requestData, List<Map<String, String>> picInfo,
List<File> files, String fileType, String key) {
// TODO Auto-generated method stub
return null;
}
/**
* 终止HTTP连接,如果想继续使用HTTP请求,需重新实例化
*/
protected void disConnection(){
mFinish = true;
}
/**
* 设置连接超时时间
* @param time 超时时间(毫秒)
*/
public void setConnectionTimeout(int time){
mTimeout = time;
}
/**
* HTTPS访问参数
*
*/
public class HTTPSParams {
private HostnameVerifier hostnameVerifier;
private SSLSocketFactory sslSocketFactory;
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
/**
* 设置信任主机,详见{@link HttpsURLConnection#setHostnameVerifier(HostnameVerifier)}
* @param hostnameVerifier
*/
public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
/**
* 设置安全链接管理,详见{@link HttpsURLConnection#setHostnameVerifier(HostnameVerifier)}
* @param hostnameVerifier
*/
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
}
/**
* 默认的安全信任管理
* 重写验证方法,取消检测ssl
*
*/
private class DefaultX509TrustManager implements X509TrustManager {
private X509TrustManager myJSSEX509TrustManager;
public DefaultX509TrustManager() throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// ks.load(new FileInputStream("trustedCerts"),
// "passphrase".toCharArray()); //----> 这是加载自己的数字签名证书文件和密码,在这里这里没有,所以不需要
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
myJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// sunJSSEX509TrustManager.checkClientTrusted(arg0, arg1);
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// sunJSSEX509TrustManager.checkServerTrusted(arg0, arg1);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// X509Certificate[] acceptedIssuers = sunJSSEX509TrustManager
// .getAcceptedIssuers();
// return acceptedIssuers;
return null;
}
}
}
private static final String TAG = "HttpGetTools";
/**
* 连接超时时间,毫秒
*/
private static final int TIME_OUT = 60000;
/**
* 网络通信缓存大小
*/
private static final int HTTP_CACHE = 1024 * 100;
private boolean mFinish;
protected HttpOnConnectionListener hol;
/**
* 网络连接超时时间
*/
private int mTimeout = TIME_OUT;
private HTTPSParams httpsParams;
public HttpGetTools(){
httpsParams = new HTTPSParams();
}
/**
* 获取HTTPS安全连接参数配置
* @return
*/
public HTTPSParams getHTTPSParams(){
return httpsParams;
}
/**
* 设置网络连接监听器
* @param listener
*/
protected void setConnectionListener(HttpOnConnectionListener listener){
this.hol = listener;
}
/**
* 获取数据
* @param urlPath 目标URL地址
* @return 发生异常返回null
*/
protected byte[] getData(String urlPath) {
if(mFinish){
throw new HttpToolsException("Connection has been terminated!");
}
HttpURLConnection http = null;
try{
URL url = new URL(urlPath);
byte[] cache = new byte[HTTP_CACHE];
http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(mTimeout);
http.setReadTimeout(mTimeout);
http.setRequestMethod("GET");
http.setRequestProperty("Charset", HTTP.UTF_8);
http.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
try{
if (http instanceof HttpsURLConnection) {
((HttpsURLConnection) http).setSSLSocketFactory(httpsParams.getSslSocketFactory() == null ?
getDefaultSSLSocketFactory() : httpsParams.getSslSocketFactory());
// Allow all hostnames
((HttpsURLConnection) http).setHostnameVerifier(httpsParams.getHostnameVerifier() == null ?
getDefaultHostnameVerifier() : httpsParams.getHostnameVerifier());
}
}catch(Exception e){
Log.e(TAG, e.toString());
}
http.connect();
final int code = http.getResponseCode();
if(code == HttpStatus.SC_OK){
Log.i(TAG, "the http resposed");
if(hol != null){
hol.onResponseOK();
}
InputStream inStream = http.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len = inStream.read(cache)) > 0) {
bos.write(cache, 0, len);
// Log.i("mFinish_len_in", ">>>>>>SSSS"+mFinish);
if(mFinish){
if(hol != null){
hol.onDisconnected();
// Log.i("mFinish_len", ">>>>>>"+mFinish);
}
return null;
}
}
bos.close();
byte[] compressData = bos.toByteArray();
if(hol != null){
if(!mFinish){
hol.onSuccessd(compressData);
}else{
hol.onDisconnected();
// Log.i("mFinish_len_down", ">>>>>>"+mFinish);
}
}
inStream.close();
return compressData;
}else{
if(hol != null && !mFinish){
hol.onResponseFailed(code);
}
}
}catch (Exception e) {
Log.e(TAG, e.toString());
if(hol != null && !mFinish){
hol.onError(e);
}
}finally{
if(http != null){
http.disconnect();
}
}
return null;
}
private SSLSocketFactory getDefaultSSLSocketFactory() throws Exception {
// Trust all certificates
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] TRUST_MANAGER = { new DefaultX509TrustManager() };
context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
SSLSocketFactory socketFactory = context.getSocketFactory();
return socketFactory;
}
private HostnameVerifier getDefaultHostnameVerifier(){
return new AllowAllHostnameVerifier();
}
/**
* 本方法用于使用get方法获取数据, 参数中的Object对象可以为空,无影响
*/
@Override
public byte[] postGetData(final String urlPath, Object part) {
return getData(urlPath);
}
/**
* 暂未实现该方法
*/
@Override
public byte[] uploadMultiPartData(String url, Map<String, String> requestData, Map<String,File> files) {
// TODO Auto-generated method stub
return null;
}
/**
* 暂未实现该方法
*/
@Override
public byte[] uploadMultiPartData(String url,
Map<String, String> requestData, List<Map<String, String>> picInfo,
List<File> files, String fileType, String key) {
// TODO Auto-generated method stub
return null;
}
/**
* 终止HTTP连接,如果想继续使用HTTP请求,需重新实例化
*/
protected void disConnection(){
mFinish = true;
}
/**
* 设置连接超时时间
* @param time 超时时间(毫秒)
*/
public void setConnectionTimeout(int time){
mTimeout = time;
}
/**
* HTTPS访问参数
*
*/
public class HTTPSParams {
private HostnameVerifier hostnameVerifier;
private SSLSocketFactory sslSocketFactory;
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
/**
* 设置信任主机,详见{@link HttpsURLConnection#setHostnameVerifier(HostnameVerifier)}
* @param hostnameVerifier
*/
public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
/**
* 设置安全链接管理,详见{@link HttpsURLConnection#setHostnameVerifier(HostnameVerifier)}
* @param hostnameVerifier
*/
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
}
/**
* 默认的安全信任管理
* 重写验证方法,取消检测ssl
*
*/
private class DefaultX509TrustManager implements X509TrustManager {
private X509TrustManager myJSSEX509TrustManager;
public DefaultX509TrustManager() throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// ks.load(new FileInputStream("trustedCerts"),
// "passphrase".toCharArray()); //----> 这是加载自己的数字签名证书文件和密码,在这里这里没有,所以不需要
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
myJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// sunJSSEX509TrustManager.checkClientTrusted(arg0, arg1);
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// sunJSSEX509TrustManager.checkServerTrusted(arg0, arg1);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// X509Certificate[] acceptedIssuers = sunJSSEX509TrustManager
// .getAcceptedIssuers();
// return acceptedIssuers;
return null;
}
}
}