本次封装只针对get和post请求。
需要的权限和依赖
<uses-permission android:name="android.permission.INTERNET"/>
implementation 'com.google.code.gson:gson:2.8.5'
准备工作:
public class HttpCode {
public static final int CODE_200 = 200;
public static final int CODE_9999 = 9999;
public static final String CODE_9999_MSG = "网络或系统异常";
}
定义错误码和提示信息。
public class NetConstant {
public static final String NULL = "null";
public static final String NULL_SLASH = "\"null\"";
}
保证接收消息不为null要用到的。
public class RequestEntity implements Serializable {
private static final String REQUEST_SUFFIX = "Request";
public String getUrlName() {
String clsName = this.getClass().getSimpleName();
if (clsName.endsWith(REQUEST_SUFFIX)) {
String action = clsName.substring(0, clsName.length() - 7);
return action.substring(0, 1).toLowerCase()+ action.substring(1);
} else {
return clsName.substring(0, 1).toLowerCase()+ clsName.substring(1);
}
}
}
public class ResponseEntity implements Serializable {
/**
* 响应码
*/
private int code;
/**
* 提示消息
*/
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
RequestEntity和ResponseEntity分别时请求体和接收数据的基类。
public class FilterGson extends MyGson {
/**
* 过滤字段
*/
private static String[] filterFields = {};
public FilterGson() {
super(filter());
}
private static Gson filter() {
return new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
for (String exclude : filterFields) {
if (exclude.equals(f.getName())) {
return true;
}
}
return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}).create();
}
}
FilterGson的filterFields用来过滤字段
public class JsonParse {
private ResponseEntity responseEntity;
private Object responseBodyResult;
public ResponseEntity getResponseEntity() {
return responseEntity;
}
public Object getResponseBodyResult() {
return responseBodyResult;
}
/**
* 请求体转请求json字符串
*
* @param requestEntity 请求对象
* @return params字符串
*/
public String toGetJson(RequestEntity requestEntity) {
StringBuilder params = new StringBuilder("?");
try {
Class cls = requestEntity.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
params.append(field.getName());
params.append("=");
params.append(field.get(requestEntity));
params.append("&");
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return params.substring(0, params.length() - 1);
}
/**
* 请求体转 请求json字符串
*
* @param requestEntity 请求消息体
* @return json字符串
*/
public String toPostJson(RequestEntity requestEntity) {
return new FilterGson().toJson(requestEntity);
}
/**
* 解析json 转对象 包括:请求头、请求体、解密
*
* @param json 完整的json字符串
* @param type 对象类型
*/
public void parseJson(String json, Type type, HttpConnectionManager.BaseResultCallback callback) {
try {
JSONObject jsonObject = new JSONObject(json);
responseEntity = new FilterGson().fromJson(json, ResponseEntity.class);
if (callback.isSuccess(responseEntity.getCode())) {
String jsonBody = jsonObject.get("data").toString();
if (NetConstant.NULL.equals(jsonBody) || NetConstant.NULL_SLASH.equals(jsonBody)) {
try {
jsonBody = "{}";
responseBodyResult = new FilterGson().fromJson(jsonBody, type);
} catch (Exception e) {
jsonBody = "[]";
responseBodyResult = new FilterGson().fromJson(jsonBody, type);
}
}else {
responseBodyResult = new FilterGson().fromJson(jsonBody, type);
}
if (responseBodyResult == null) {
responseEntity.setCode(HttpCode.CODE_9999);
responseEntity.setMsg(HttpCode.CODE_9999_MSG);
}
}
} catch (Exception e) {
e.printStackTrace();
responseEntity.setCode(HttpCode.CODE_9999);
responseEntity.setMsg(HttpCode.CODE_9999_MSG);
}
}
}
public class MyGson {
private Gson gson;
public MyGson() {
this.gson = new Gson();
}
public MyGson(Gson gson) {
this.gson = gson;
}
public <T> T fromJson(String json, Type typeOfT) {
try {
return gson.fromJson(json, typeOfT);
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
public String toJson(Object src) {
return gson.toJson(src);
}
}
负责具体的数据解析。
主体:
public class HttpConnectionManager {
private ThreadPoolExecutor threadPoolExecutor;
private Handler mHandler;
private HttpConnectionManager() {
}
public static HttpConnectionManager getInstance() {
return HttpHolder.HTTP_CONNECTION_MANAGER;
}
private static class HttpHolder {
private static final HttpConnectionManager HTTP_CONNECTION_MANAGER = new HttpConnectionManager();
}
/**
* 初始化线程池
*/
public synchronized void init() {
if (null == threadPoolExecutor) {
threadPoolExecutor = new ThreadPoolExecutor(3, 5, 0L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), new CheckThreadFactory());
}
if (null == mHandler) {
mHandler = new Handler(Looper.getMainLooper());
}
}
/**
* get请求
*
* @param url 地址
* @param requestEntity 请求体
*/
public void get(final String url, RequestEntity requestEntity, final BaseResultCallback callback) {
final String params = new JsonParse().toGetJson(requestEntity);
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
HttpURLConnection mHttpUrlConnection = null;
try {
URL mUrl = new URL(url + params);
mHttpUrlConnection = (HttpURLConnection) mUrl.openConnection();
//设置连接超时时间
mHttpUrlConnection.setConnectTimeout(15000);
//设置读取超时时间
mHttpUrlConnection.setReadTimeout(15000);
//设置请求方式
mHttpUrlConnection.setRequestMethod("GET");
//添加Header
mHttpUrlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 设置输入可用
mHttpUrlConnection.setDoInput(true);
// 设置输出可用
mHttpUrlConnection.setDoOutput(true);
// 设置缓存不可用
mHttpUrlConnection.setUseCaches(false);
//开始连接
mHttpUrlConnection.connect();
int responseCode = mHttpUrlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = mHttpUrlConnection.getInputStream();
String result = inputStreamString(inputStream);
if (null != result && null != callback) {
JsonParse jsonParse = new JsonParse();
jsonParse.parseJson(result, callback.mType, callback);
ResponseEntity responseEntity = jsonParse.getResponseEntity();
if (HttpCode.CODE_200 == responseEntity.getCode() || callback.isSuccess(responseEntity.getCode())) {
sendSuccessCallBack(callback, jsonParse.getResponseBodyResult());
} else {
sendFailCallback(callback, responseEntity.getCode(), responseEntity.getMsg());
}
} else {
sendFailCallback(callback, HttpCode.CODE_9999, HttpCode.CODE_9999_MSG);
}
} else {
sendFailCallback(callback, HttpCode.CODE_9999, HttpCode.CODE_9999_MSG);
}
} catch (IOException e) {
e.printStackTrace();
sendFailCallback(callback, HttpCode.CODE_9999, HttpCode.CODE_9999_MSG);
} finally {
if (null != mHttpUrlConnection) {
mHttpUrlConnection.disconnect();
}
}
}
});
}
public void post(final String url, RequestEntity requestEntity, final BaseResultCallback callback) {
final String json = new JsonParse().toPostJson(requestEntity);
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
HttpURLConnection mHttpUrlConnection = null;
try {
URL mUrl = new URL(url);
mHttpUrlConnection = (HttpURLConnection) mUrl.openConnection();
//设置连接超时时间
mHttpUrlConnection.setConnectTimeout(15000);
//设置读取超时时间
mHttpUrlConnection.setReadTimeout(15000);
//设置请求方式
mHttpUrlConnection.setRequestMethod("POST");
//添加Header
mHttpUrlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 设置输入可用
mHttpUrlConnection.setDoInput(true);
// 设置输出可用
mHttpUrlConnection.setDoOutput(true);
// 设置缓存不可用
mHttpUrlConnection.setUseCaches(false);
//开始连接
mHttpUrlConnection.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mHttpUrlConnection.getOutputStream(), "UTF-8"));
writer.write(json);
writer.close();
int responseCode = mHttpUrlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = mHttpUrlConnection.getInputStream();
String result = inputStreamString(inputStream);
if (null != result && null != callback) {
JsonParse jsonParse = new JsonParse();
jsonParse.parseJson(result, callback.mType, callback);
ResponseEntity responseEntity = jsonParse.getResponseEntity();
if (HttpCode.CODE_200 == responseEntity.getCode() || callback.isSuccess(responseEntity.getCode())) {
sendSuccessCallBack(callback, jsonParse.getResponseBodyResult());
} else {
sendFailCallback(callback, responseEntity.getCode(), responseEntity.getMsg());
}
}else {
sendFailCallback(callback, HttpCode.CODE_9999, HttpCode.CODE_9999_MSG);
}
} else {
sendFailCallback(callback, HttpCode.CODE_9999, HttpCode.CODE_9999_MSG);
}
} catch (IOException e) {
e.printStackTrace();
sendFailCallback(callback, HttpCode.CODE_9999, HttpCode.CODE_9999_MSG);
} finally {
if (null != mHttpUrlConnection) {
mHttpUrlConnection.disconnect();
}
}
}
});
}
/**
* UI线程中执行操作成功回调
*
* @param callback 回调类
* @param responseBody 服务器响应的body
*/
private void sendSuccessCallBack(final BaseResultCallback callback, final Object responseBody) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onSuccess(responseBody);
}
}
});
}
/**
* UI线程中执行操作失败回调
*
* @param callback 回调类
* @param code 错误码
* @param msg 错误信息
*/
private void sendFailCallback(final BaseResultCallback callback, final int code, final String msg) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onFailure(code, msg);
}
}
});
}
/**
* 字节流转换成字符串
*
* @param inputStream 输入流
* @return 字符串
*/
private String inputStreamString(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
try {
while (-1 != (len = inputStream.read(bytes))) {
outputStream.write(bytes, 0, len);
}
return new String(outputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private static class CheckThreadFactory implements ThreadFactory {
private AtomicInteger atomicInteger = new AtomicInteger();
@Override
public Thread newThread(@NonNull Runnable r) {
int index = atomicInteger.incrementAndGet();
System.out.println("create no " + index + " thread");
return new Thread(r, "Thread-" + index);
}
}
/**
* http请求回调类,回调方法在UI线程中执行
*
* @param <T> ResponseBody的子类
*/
public static abstract class BaseResultCallback<T> {
Type mType;
public BaseResultCallback() {
mType = getSuperclassTypeParameter(getClass());
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Enter generics in BaseResultCallback");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
/**
* 判断服务器返回code是否为成功
*
* @param code 返回码
* @return 是否成功
*/
public boolean isSuccess(int code) {
return HttpCode.CODE_200 == code;
}
/**
* 请求成功回调
*
* @param result 响应结果实体或集合
*/
public abstract void onSuccess(T result);
/**
* 请求失败回调
*
* @param code 错误码
* @param msg 失败原因
*/
public abstract void onFailure(int code, String msg);
}
}
HttpManager
public class HttpManager {
public static void init(String ip, String post) {
HttpConnectionManager.getInstance().init();
baseIp = ip;
basePort = post;
}
private static String baseIp;
private static String basePort;
private static String getRequestUrl(String action) {
String baseUrl = "http://%s:%s/online/%s/";
return String.format(baseUrl, baseIp, basePort, action);
}
public static void get(RequestEntity requestEntity, HttpConnectionManager.BaseResultCallback callback) {
HttpConnectionManager.getInstance().get(getRequestUrl(requestEntity.getUrlName()), requestEntity, callback);
}
public static void post(RequestEntity requestEntity, HttpConnectionManager.BaseResultCallback callback) {
HttpConnectionManager.getInstance().post(getRequestUrl(requestEntity.getUrlName()), requestEntity, callback);
}
}
到这就算封装完成。
例子:
首先初始化
public class BaseApp extends Application {
@Override
public void onCreate() {
super.onCreate();
HttpManager.init("ip", "port");
}
}
然后创建实体
public class LoginRequest extends RequestEntity {
public String userName;
public String password;
}
public class LoginResponse extends ResponseEntity {
public String username;
public String uid;
public String rolename;
public String rid;
}
最后调用
LoginRequest loginRequest = new LoginRequest();
loginRequest.userName = "张三";
loginRequest.password = MD5("123456");
HttpManager.post(loginRequest, new HttpConnectionManager.BaseResultCallback<LoginResponse>() {
@Override
public void onSuccess(LoginResponse result) {
Log.d("===",result.user.username);
}
@Override
public void onFailure(int code, String msg) {
}
});