This commit is contained in:
2025-11-18 15:12:24 +08:00
parent c173c425ce
commit a7d2035e70
1361 changed files with 367452 additions and 0 deletions
@@ -0,0 +1,188 @@
package cn.shangyu.gdxzExpert.http;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
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.entity.HttpEntityWrapper;
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.protocol.HttpContext;
public class HttpClientFactory {
/** http请求最大并发连接数 */
private static final int MAX_CONNECTIONS = 10;
/** 超时时间 */
private static final int TIMEOUT = 10 * 1000;
/** 缓存大小 */
private static final int SOCKET_BUFFER_SIZE = 8 * 1024; // 8KB
/** 错误尝试次数,错误异常表请在RetryHandler添加 */
private static final int MAX_RETRIES = 5;
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
public static DefaultHttpClient create(boolean isHttps) {
HttpParams params = createHttpParams();
DefaultHttpClient httpClient = null;
if (isHttps) {
// 支持http与https
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// ThreadSafeClientConnManager线程安全管理类
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
httpClient = new DefaultHttpClient(cm, params);
} else {
httpClient = new DefaultHttpClient(params);
}
return httpClient;
}
private static HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向
ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
return params;
}
private static void createHttpClient(DefaultHttpClient httpClient) {
// 添加request的拦截器,添加必要的头信息
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) {
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
}
});
// 添加response拦截器,预先对response进行一些处理
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(HttpResponse response, HttpContext context) {
final HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
// 如果是以GZIP压缩的数据,利用内部的填充器包装一层Gzip的流
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});
// 设置重试次数
httpClient.setHttpRequestRetryHandler(new HttpRetry(MAX_RETRIES));
}
/** 当服务器返回的数据是以Gzip压缩的过后的数据,填充Response返回的实体数据 (Description),则返回GZIP解压流 */
private static class InflatingEntity extends HttpEntityWrapper {
public InflatingEntity(HttpEntity wrapped) {
super(wrapped);
}
@Override
public InputStream getContent() throws IOException {
return new GZIPInputStream(wrappedEntity.getContent());
}
// 因为数据是压缩数据,所以实际长度无法估计,可以返回-1
@Override
public long getContentLength() {
return -1;
}
}
/** 自定义的安全套接字协议的实现,目前采用默认的,未使用到 */
private static class SSLSocketFactoryEx extends SSLSocketFactory {
// 此类的实例表示安全套接字协议的实现,它充当用于安全套接字工厂或 SSLEngine 的工厂。用可选的一组密钥和信任管理器及安全随机字节源初始化此类。
SSLContext sslContext = SSLContext.getInstance("TLS");
public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
// TrustManager负责管理做出信任决定时使用的的信任材料,也负责决定是否接受同位体提供的凭据。
// X509TrustManager此接口的实例管理使用哪一个 X509 证书来验证远端的安全套接字。决定是根据信任的证书授权、证书撤消列表、在线状态检查或其他方式做出的。
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 {
// 给出同位体提供的部分或完整的证书链,构建到可信任的根的证书路径,并且返回是否可以确认和信任将其用于基于验证类型的客户端 SSL 验证。
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
// 给出同位体提供的部分或完整的证书链,构建到可信任的根的证书路径,并且返回是否可以确认和信任将其用于基于验证类型的服务器 SSL 验证。
}
};
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();
}
}
}
@@ -0,0 +1,386 @@
package cn.shangyu.gdxzExpert.http;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import cn.shangyu.gdxzExpert.utils.IoUtils;
import cn.shangyu.gdxzExpert.utils.StringUtil;
public class HttpHelper {
// public static final String URL = "http://10.0.2.2:8080/";
/** get请求,获取返回字符串内容 */
public static HttpResult get(String url) {
HttpGet httpGet = new HttpGet(url);
return execute(url, httpGet);
}
/** get请求,获取返回字符串内容 */
public static HttpResult tokenget(String url) {
HttpGet httpGet = new HttpGet(url);
return execute(url, httpGet);
}
/** post请求,获取返回字符串内容 */
public static HttpResult post(String url,
List<BasicNameValuePair> parameters) {
HttpPost httpPost = new HttpPost(url);
if (parameters != null) {
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return execute(url, httpPost);
}
/** post请求,获取返回字符串内容 */
public static HttpResult tokenPost(String url,
List<BasicNameValuePair> parameters, String token) {
HttpPost httpPost = new HttpPost(url);
if (parameters != null) {
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.addHeader("token", token); // 认证token
httpPost.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return execute(url, httpPost);
}
/**
*
* loadData 采用xutils的方法获取,请求服务器
*
* @param method
* @param url
* @param params
* @param callback
* void
* @return
*/
public static HttpUtils http = new HttpUtils();
//
public static HttpHandler<String> loadData(HttpRequest.HttpMethod method,
String url, RequestParams params, RequestCallBack<String> callback) {
if (http == null) {
http = new HttpUtils();
}
http.configCurrentHttpCacheExpiry(1000 * 1);
// 设置线程数
http.configRequestThreadPoolSize(10);
if (params != null) {
// if (params.getQueryStringParams() != null)
// LogUtil.d(url + params.getQueryStringParams().toString());
} else {
params = new RequestParams();
}
// if (0 == CommonUtil.isNetworkAvailable(UIUtils.getContext())) {
// ToastUtil.showToast("无网络,请检查网络连接!");
// }
// else {
// http.send(method, url, params, callback);
// }
HttpHandler<String> cancleHttp = http.send(method, url, params,callback);
// if(cancleHttp!=null){
// cancleHttp.cancel();//取消网络请求
// }
return cancleHttp;
}
// /** post请求,上传图片和文字。获取返回字符串内容 */
// /**
// * 仅同时上传文件和参数时使用
// * @param url 请求地址
// * @param param 参数
// * @param file 文件
// * @return 服务器端返回的
// */
//
// public static String postTextAndFile(String url, Map<String, String>
// param,File file) {
// HttpPost httpPost = new HttpPost(url);
// HttpClient httpClient=new DefaultHttpClient();
// MultipartEntity entity = new MultipartEntity();
// if (param != null && !param.isEmpty()) {
// for (Map.Entry<String, String> entry : param.entrySet()) {
// try {
// if (entry.getValue() != null
// && entry.getValue().trim().length() > 0) {
// entity.addPart(entry.getKey(),new StringBody(entry.getValue(),
// Charset.forName(org.apache.http.protocol.HTTP.UTF_8)));
// }
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
// // 添加文件参数
// if (file != null && file.exists()) {
// entity.addPart("file", new FileBody(file));
// }
// httpPost.setEntity(entity);
// try {
// HttpResponse response = httpClient.execute(httpPost);
// int stateCode = response.getStatusLine().getStatusCode();
// if (stateCode == HttpStatus.SC_OK) {
// HttpEntity result = response.getEntity();
// if (result != null) {
// InputStream is = result.getContent();
// String str = stream2String(is);
// return str;
// }
// }
// } catch (ClientProtocolException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IllegalStateException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return null;
// }
public static String stream2String(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] bys = new byte[1024];
try {
while ((len = is.read(bys)) != -1) {
baos.write(bys, 0, len);
}
return new String(baos.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
*
* @param url
* 下载路径
* @return
*/
public static HttpResult download(String url) {
HttpGet httpGet = new HttpGet(url);
return execute(url, httpGet);
}
/**
* 执行网络访问 retryHandler 重试机制,暂且不考虑,如有需要在打开
*
* @param url
* @param requestBase
* @return
*/
private static HttpResult execute(String url, HttpRequestBase requestBase) {
boolean isHttps = url.startsWith("https://");// 判断是否需要采用https\
AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
// httpClient = (AbstractHttpClient) WebClientDevWrapper.wrapClient(httpClient);
HttpContext httpContext = new SyncBasicHttpContext(
new BasicHttpContext());
HttpRequestRetryHandler retryHandler = httpClient
.getHttpRequestRetryHandler();// 获取重试机制
int retryCount = 0;
boolean retry = true;
while (retry) {
try {
HttpResponse response = httpClient.execute(requestBase,httpContext);// 访问网络
if (response != null) {
return new HttpResult(response, httpClient, requestBase);
}
} catch (Exception e) {
IOException ioException = new IOException(e.getMessage());
// retry = retryHandler.retryRequest(ioException, ++retryCount,
// httpContext);// 把错误异常交给重试机制,以判断是否需要采取从事
retry = false;
e.printStackTrace();
}
}
return null;
}
/** http的返回结果的封装,可以直接从中获取返回的字符串或者流 */
public static class HttpResult {
private HttpResponse mResponse;
private InputStream mIn;
private String mStr;
private HttpClient mHttpClient;
private HttpRequestBase mRequestBase;
public HttpResult(HttpResponse response, HttpClient httpClient,
HttpRequestBase requestBase) {
mResponse = response;
mHttpClient = httpClient;
mRequestBase = requestBase;
}
public int getCode() {
StatusLine status = mResponse.getStatusLine();
return status.getStatusCode();
}
/** 从结果中获取字符串,一旦获取,会自动关流,并且把字符串保存,方便下次获取 */
public String getString() {
if (!StringUtil.isEmpty(mStr)) {
return mStr;
}
InputStream inputStream = getInputStream();
ByteArrayOutputStream out = null;
if (inputStream != null) {
try {
out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
byte[] data = out.toByteArray();
mStr = new String(data, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
IoUtils.close(out);
close();
}
}
return mStr;
}
/** 获取流,需要使用完毕后调用close方法关闭网络连接 */
public InputStream getInputStream() {
if (mIn == null && getCode() < 300) {
HttpEntity entity = mResponse.getEntity();
try {
mIn = entity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
}
return mIn;
}
/** 关闭网络连接 */
public void close() {
if (mRequestBase != null) {
mRequestBase.abort();
}
IoUtils.close(mIn);
if (mHttpClient != null) {
mHttpClient.getConnectionManager().closeExpiredConnections();
}
}
}
/** http的返回结果的封装,可以直接从中获取返回的字符串或者流 */
// public static class HttpResult {
// private HttpResponse mResponse;
// private InputStream mIn;
// private String mStr;
// private HttpClient mHttpClient;
// private HttpRequestBase mRequestBase;
//
// public HttpResult(HttpResponse response, HttpClient httpClient,
// HttpRequestBase requestBase) {
// mResponse = response;
// mHttpClient = httpClient;
// mRequestBase = requestBase;
// }
//
// public int getCode() {
// StatusLine status = mResponse.getStatusLine();
// return status.getStatusCode();
// }
//
// /** 从结果中获取字符串,一旦获取,会自动关流,并且把字符串保存,方便下次获取 */
// public String getString() {
// if (!StringUtil.isEmpty(mStr)) {
// return mStr;
// }
// InputStream inputStream = getInputStream();
// ByteArrayOutputStream out = null;
// if (inputStream != null) {
// try {
// out = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024 * 4];
// int len = -1;
// while ((len = inputStream.read(buffer)) != -1) {
// out.write(buffer, 0, len);
// }
// byte[] data = out.toByteArray();
// mStr = new String(data, "utf-8");
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// IoUtils.close(out);
// close();
// }
// }
// return mStr;
// }
//
// /** 获取流,需要使用完毕后调用close方法关闭网络连接 */
// public InputStream getInputStream() {
// if (mIn == null && getCode() < 300) {
// HttpEntity entity = mResponse.getEntity();
// try {
// mIn = entity.getContent();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return mIn;
// }
//
// /** 关闭网络连接 */
// public void close() {
// if (mRequestBase != null) {
// mRequestBase.abort();
// }
// IoUtils.close(mIn);
// if (mHttpClient != null) {
// mHttpClient.getConnectionManager().closeExpiredConnections();
// }
// }
// }
}
@@ -0,0 +1,78 @@
package cn.shangyu.gdxzExpert.http;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashSet;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import android.os.SystemClock;
public class HttpRetry implements HttpRequestRetryHandler{
// 重试休息的时间
private static final int RETRY_SLEEP_TIME_MILLIS = 1000;
// 网络异常,继续
private static HashSet<Class<?>> exceptionWhitelist = new HashSet<Class<?>>();
// 用户异常,不继续(如,用户中断线程)
private static HashSet<Class<?>> exceptionBlacklist = new HashSet<Class<?>>();
static {
// 以下异常不需要重试,这样异常都是用于造成或者是一些重试也无效的异常
exceptionWhitelist.add(NoHttpResponseException.class);// 连上了服务器但是没有Response
exceptionWhitelist.add(UnknownHostException.class);// host出了问题,一般是由于网络故障
exceptionWhitelist.add(SocketException.class);// Socket问题,一般是由于网络故障
// 以下异常可以重试
exceptionBlacklist.add(InterruptedIOException.class);// 连接中断,一般是由于连接超时引起
exceptionBlacklist.add(SSLHandshakeException.class);// SSL握手失败
}
private final int maxRetries;
public HttpRetry(int maxRetries) {
this.maxRetries = maxRetries;
}
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
boolean retry = true;
// 请求是否到达
Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if (executionCount > maxRetries) {
// 尝试次数超过用户定义的测试
retry = false;
} else if (exceptionBlacklist.contains(exception.getClass())) {
// 线程被用户中断,则不继续尝试
retry = false;
} else if (exceptionWhitelist.contains(exception.getClass())) {
// 出现的异常需要被重试
retry = true;
} else if (!sent) {
// 请求没有到达
retry = true;
}
// 如果需要重试
if (retry) {
// 获取request
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
// POST请求难道就不需要重试?
//retry = currentReq != null && !"POST".equals(currentReq.getMethod());
retry = currentReq != null;
}
if (retry) {
// 休眠1秒钟后再继续尝试
SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
} else {
exception.printStackTrace();
}
return retry;
}
}
@@ -0,0 +1,5 @@
package cn.shangyu.gdxzExpert.http;
public interface OnCallBackFromActivity {
void getmessage(Boolean receive_notice);
}
@@ -0,0 +1,13 @@
package cn.shangyu.gdxzExpert.http;
import java.io.Serializable;
/**
*
* @author zhaodewei
* 结果的回调到 activity
*
*/
public interface OnCallBackFromNet extends Serializable{
public void onCallbackFromThread(String resultJson);
public void onCallBackFromThread(String resultJson, int resultCode);
}