github地址:https://github.com/Dragonxwl/MyBasePro
1.原理以及目录结构
AsyncTask + HttpURLConnection 封装网络请求
2.BaseTask 线程封装
public class BaseTask extends AsyncTask<Integer, Object, Object> {
protected TaskListener mListener = null;
protected int mTaskId = 0;
private boolean mIsRunning = false;
private Object mData = null;
public BaseTask() {
super();
}
public BaseTask(int taskId) {
super();
this.mTaskId = taskId;
}
public BaseTask(int taskId, Object data) {
super();
this.mTaskId = taskId;
this.mData = data;
}
public static void run(TaskListener listener) {
run(listener, null);
}
public static void run(TaskListener listener, Object data) {
BaseTask task = new BaseTask();
task.setListener(listener);
task.setData(data);
task.execute();
}
public void setListener(TaskListener listener) {
mListener = listener;
}
public void setData(Object data) {
mData = data;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mListener != null) {
mListener.onTaskPrepare(mTaskId, mData);
}
}
@Override
protected Object doInBackground(Integer... params) {
mIsRunning = true;
Object result = doRunning();
mIsRunning = false;
return result;
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mListener != null) {
mListener.onTaskCancelled(mTaskId);
mListener = null;
}
mIsRunning = false;
}
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.onTaskResult(mTaskId, result);
mListener = null;
}
mIsRunning = false;
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
if (mListener != null) {
mListener.onTaskProgress(mTaskId, values);
}
}
public void progress(Object... values) {
publishProgress(values);
}
public void release() {
if (mIsRunning) {
this.cancel(false);
mIsRunning = false;
}
}
protected Object doRunning() {
if (mListener != null) {
return mListener.onTaskRunning(mTaskId, mData);
}
return null;
}
public static interface TaskListener {
public void onTaskPrepare(int taskId, Object data);
public Object onTaskRunning(int taskId, Object data);
public void onTaskProgress(int taskId, Object... values);
public void onTaskResult(int taskId, Object result);
public void onTaskCancelled(int taskId);
}
public static class TaskAdapter implements TaskListener {
public void onTaskPrepare(int taskId, Object data) {
}
public Object onTaskRunning(int taskId, Object data) {
return null;
}
public void onTaskProgress(int taskId, Object... values) {
}
public void onTaskResult(int taskId, Object result) {
}
public void onTaskCancelled(int taskId) {
}
}
}
3.HttpUtilsHttpURLConnection 请求构造封装
public class HttpUtilsHttpURLConnection {
/*
* Post 请求
* urlStr:网址
* parms:提交数据
* return:网页源码
* */
public static String HttpPost(String urlStr, JSONObject parms) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
// 设置文件类型:
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//设置token
if (!noTokenList.contains(urlStr)) {
connection.setRequestProperty("access-token",
ACConfig.getInstance().getAccessToken());
}
// 设置接收类型否则返回415错误
connection.setRequestProperty("accept", "application/json");
String Json = parms.toString();
// 往服务器里面发送数据
if (Json != null && !TextUtils.isEmpty(Json)) {
byte[] writebytes = Json.getBytes();
// 设置文件长度
connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
OutputStream outputStream = connection.getOutputStream();
outputStream.write(Json.getBytes());
outputStream.flush();
outputStream.close();
}
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String temp;
while ((temp = reader.readLine()) != null) {
sb.append(temp);
}
reader.close();
}
connection.disconnect();
} catch (Exception e) {
return e.toString();
}
return sb.toString();
}
/*
* Get 请求
* urlStr:网址
* parms:提交数据
* return:网页源码
* */
public static String HttpGet(String urlStr, Map<String, String> parms) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(urlStr + MapToGetStr(parms));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
//设置token
if (!noTokenList.contains(urlStr)) {
connection.setRequestProperty("access-token",
ACConfig.getInstance().getAccessToken());
}
int code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String temp;
while ((temp = reader.readLine()) != null) {
sb.append(temp);
}
reader.close();
}
connection.disconnect();
} catch (Exception e) {
return e.toString();
}
return sb.toString();
}
/**
* 将map转换成key1=value1&key2=value2的形式
*
* @param map
* @return
* @throws UnsupportedEncodingException
*/
private static String MapToGetStr(Map<String, String> map) throws
UnsupportedEncodingException {
if (map != null) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (Map.Entry<String, String> entry : map.entrySet()) {
if (isFirst) {
isFirst = false;
sb.append("?");
} else {
sb.append("&");
}
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return sb.toString();
} else {
return "";
}
}
}
4.MyServer
public class MyServer {
/**
* 接口用途:获取预配置信息
*/
public static Object GET_getByAppId(Map<String, String> params) {
String response = HttpUtilsHttpURLConnection.HttpGet(Application.GetHost()
+ Protocol.GET_getByAppId + "/8/" + Application.getAppVersionCode(Application.getContext()), params);
if (response != null) {
try {
Gson gson = new Gson();
return gson.fromJson(response, ProfileResultBean.class);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
/**
* 接口用途:新增日志
*/
public static Object Post_stuGetTokenByPhoneAndSms(JSONObject params) {
String response = HttpUtilsHttpURLConnection.HttpPost(Application.GetHost()
+ Protocol.Post_stuGetTokenByPhoneAndSms, params);
if (response != null) {
try {
Gson gson = new Gson();
return gson.fromJson(response, LoginBean.class);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
/**
* 接口用途:上传用户安装的非系统app
*/
public static Object Post_GetUserApps(JSONObject params) {
String response = HttpUtilsHttpURLConnection.HttpPost(Application.GetHost()
+ Protocol.Post_GetUserApps, params);
if (response != null) {
try {
Gson gson = new Gson();
return gson.fromJson(response, BaseBean.class);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
5.Protocol
public class Protocol {
// 学生登录-根据短信验证码
public static String Post_stuGetTokenByPhoneAndSms = "/ac-common/oauth/sms/stu";
// 获取预配置信息
public static String GET_getByAppId = "/ac-client/profile";
// 上传用户应用列表
public static String Post_GetUserApps = "/ac-client/user-apps/save";
}
6.httpDemoActivity
Demo页面 执行网络请求并显示结果
public void GET_getByAppId() {
if (GET_getByAppIdFlag) {
GET_getByAppIdFlag = false;
BaseTask.run(new BaseTask.TaskListener() {
@Override
public Object onTaskRunning(int taskId, Object data) {
Map<String, String> params = new HashMap<>();
params.put("channelName", StringUtils.getChannelName(Application.getContext()));
return myServer.GET_getByAppId(params);
}
@Override
public void onTaskResult(int taskId, Object result) {
GET_getByAppIdFlag = true;
if (result instanceof ProfileResultBean) {
ProfileResultBean mProfileResultBean = (ProfileResultBean) result;
TextView_value.setText(mProfileResultBean.data.dbCode + "");
}
}
@Override
public void onTaskProgress(int taskId, Object... values) {
}
@Override
public void onTaskPrepare(int taskId, Object data) {
}
@Override
public void onTaskCancelled(int taskId) {
GET_getByAppIdFlag = true;
}
});
}
}
7.混淆
proguard-rules.pro 文件
# gson entity
-keep class com.xwl.mybasepro.bean.** {*;}
8.AndroidManifest 配置文件申请权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />