xUtils封装http各种操作

  1. package com.shyky.educ.helper;
  2.  
  3. import java.io.File;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URLEncoder;
  6. import java.text.DecimalFormat;
  7.  
  8. import android.app.ProgressDialog;
  9. import android.content.Context;
  10. import android.os.Handler;
  11. import android.os.Message;
  12. import android.widget.Button;
  13.  
  14. import com.lidroid.xutils.HttpUtils;
  15. import com.lidroid.xutils.exception.HttpException;
  16. import com.lidroid.xutils.http.RequestParams;
  17. import com.lidroid.xutils.http.ResponseInfo;
  18. import com.lidroid.xutils.http.callback.RequestCallBack;
  19. import com.lidroid.xutils.http.client.HttpRequest;
  20. import com.lidroid.xutils.util.PreferencesCookieStore;
  21. import com.shyky.educ.R;
  22. import com.shyky.educ.common.Configs;
  23. import com.shyky.educ.common.Constants;
  24. import com.shyky.educ.dialog.CommonAlertDialog;
  25. import com.shyky.educ.dialog.CommonLoadingDialog;
  26. import com.shyky.educ.view.CommonToast;
  27.  
  28. /**
  29. * 快速开发框架XUtils帮助类,此类封装了该框架的各种操作
  30. *
  31. * @author Shyky
  32. * @date 2014-11-19
  33. */
  34. public class XUtilsHelper {
  35.  
  36. private Context context;
  37. private Handler handler;
  38. private String url;
  39. /**
  40. * 返回文本的编码, 默认编码UTF-8
  41. */
  42. private HttpUtils httpUtils;
  43. private CommonLoadingDialog loadingDialog;
  44. private CommonAlertDialog alertDialog;
  45. private ProgressDialog progressDialog;
  46. /**
  47. * 请求参数,默认编码UTF-8
  48. */
  49. private RequestParams params;
  50. private String filename;
  51.  
  52. /**
  53. * 构造方法
  54. *
  55. * @param context
  56. *            用于程序上下文,必须用当前Activity的this对象,否则报错
  57. * @param url
  58. *            网络资源地址
  59. * @param handler
  60. *            消息处理对象,用于请求完成后的怎么处理返回的结果数据
  61. */
  62. public XUtilsHelper(Context context, String url, Handler handler) {
  63. this.context = context;
  64. try {
  65. // 保存网络资源文件名,要在转码之前保存,否则是乱码
  66. filename = url.substring(url.lastIndexOf("/") + 1, url.length());
  67. // 解决中文乱码问题,地址中有中文字符造成乱码问题
  68. String old_url = URLEncoder.encode(url, "GBK");
  69. // 替换地址中的特殊字符
  70. String new_url = old_url.replace("%3A", ":").replace("%2F", "/")
  71. .replace("%3F", "?").replace("%3D", "=")
  72. .replace("%26", "&").replace("%2C", ",")
  73. .replace("%20", " ").replace("+", "%20")
  74. .replace("%2B", "+").replace("%23", "#")
  75. .replace("#", "%23");
  76. this.url = new_url;
  77. } catch (UnsupportedEncodingException e) {
  78. e.printStackTrace();
  79. }
  80. this.httpUtils = XutilsHttpClient.getInstence(context);
  81. this.handler = handler;
  82. this.loadingDialog = new CommonLoadingDialog(context,
  83. R.layout.activity_input_loading);
  84. this.progressDialog = new ProgressDialog(context);
  85. this.alertDialog = new CommonAlertDialog(context);
  86. this.params = new RequestParams("GBK"); // 编码与服务器端字符编码一致为gbk
  87. }
  88.  
  89. public void sendGet() {
  90. httpUtils.send(HttpRequest.HttpMethod.GET, url,
  91. new RequestCallBack<String>() {
  92.  
  93. @Override
  94. public void onFailure(HttpException arg0, String arg1) {
  95.  
  96. }
  97.  
  98. @Override
  99. public void onSuccess(ResponseInfo<String> arg0) {
  100.  
  101. }
  102. });
  103. }
  104.  
  105. /**
  106. * POST请求时需要设置提交参数,解决了中文乱码设置了字符编码为GBK
  107. *
  108. * @param namevlues
  109. *            提交参数/值字符串二维数组
  110. */
  111. public void setRequestParams(String[][] namevlues) {
  112. for (int i = 0; i < namevlues.length; i++)
  113. params.addBodyParameter(namevlues[i][0], namevlues[i][1]);
  114. }
  115.  
  116. /**
  117. * POST方式请求服务器资源
  118. *
  119. * @param dialogTitle
  120. *            加载中对话框显示标题文字
  121. * @param dialogNotingTitle
  122. *            提示对话框标题文字
  123. */
  124. public void sendPost(final String dialogTitle,
  125. final String dialogNotingTitle) {
  126.  
  127. if (dialogTitle != null) {
  128. loadingDialog.showDialog(dialogTitle, R.style.loading_dialog,
  129. R.anim.loading, false);
  130. }
  131. httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
  132. new RequestCallBack<String>() {
  133.  
  134. @Override
  135. public void onSuccess(ResponseInfo<String> arg0) {
  136. Message msg = Message.obtain();
  137. if (arg0.statusCode == 200) {
  138. // 无数据判断
  139. if (Configs.HTTP_RESPONSE.trim().equals(
  140. arg0.result.trim())
  141. || arg0.result.trim().startsWith(
  142. "<response totalRows='0'>".trim())
  143. || arg0.result.trim().contains(
  144. "<items totalRows='0'>".trim())
  145. || arg0.result.trim().contains(
  146. "<items totalRows='0'".trim())
  147. || "<classes/>".trim().equals(
  148. arg0.result.trim())
  149. || "<classes/>".trim().equals(
  150. arg0.result.trim())
  151. || "[{\"totalRows\":0}]".trim().equals(
  152. arg0.result.trim())) {
  153.  
  154. if (dialogTitle != null)
  155. loadingDialog.dismiss();
  156. // 需要判断是否要显示模式确认对话框
  157. if (dialogNotingTitle != null) {
  158. alertDialog
  159. .showConfirmDialog(
  160. dialogNotingTitle, "确认",
  161. null, null);
  162. }
  163. msg.obj = Constants.TAG_NOTHING;
  164. } else {
  165. if (dialogTitle != null)
  166. loadingDialog.dismiss();
  167. msg.obj = arg0.result;
  168. }
  169. } else {
  170. if (dialogTitle != null)
  171. loadingDialog.dismiss();
  172. msg.obj = Constants.TAG_FAILURE;
  173. }
  174. handler.sendMessage(msg);
  175. }
  176.  
  177. @Override
  178. public void onFailure(HttpException arg0, String arg1) {
  179. if (dialogTitle != null)
  180. loadingDialog.dismiss();
  181. arg0.printStackTrace();
  182. Message msg = Message.obtain();
  183. msg.obj = Constants.TAG_FAILURE;
  184. handler.sendMessage(msg);
  185. }
  186. });
  187. }
  188.  
  189. /**
  190. * 上传文件到服务器
  191. *
  192. * @param param
  193. *            提交参数名称
  194. * @param file
  195. *            要上传的文件对象
  196. */
  197. public void uploadFile(String param, File file) {
  198. progressDialog.setTitle("上传文件中,请稍等...");
  199. progressDialog.setCancelable(false);
  200. progressDialog.setCanceledOnTouchOutside(false);
  201. // 设置进度条风格,风格为水平进度条
  202. progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  203. params.addBodyParameter(param, file);
  204. httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
  205. new RequestCallBack<String>() {
  206.  
  207. @Override
  208. public void onStart() {
  209. progressDialog.show();
  210. }
  211.  
  212. @Override
  213. public void onLoading(long total, long current,
  214. boolean isUploading) {
  215. // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
  216. progressDialog.setIndeterminate(false);
  217. progressDialog.setProgress((int) current);
  218. progressDialog.setMax((int) total);
  219. }
  220.  
  221. @Override
  222. public void onSuccess(ResponseInfo<String> arg0) {
  223. System.out.println(arg0.statusCode);
  224. System.out.println(arg0.result);
  225. progressDialog.dismiss();
  226. Message msg = Message.obtain();
  227. msg.obj = arg0.result;
  228. handler.sendMessage(msg);
  229. }
  230.  
  231. @Override
  232. public void onFailure(HttpException arg0, String arg1) {
  233. progressDialog.dismiss();
  234. arg0.printStackTrace();
  235. Message msg = Message.obtain();
  236. msg.obj = Constants.TAG_FAILURE;
  237. handler.sendMessage(msg);
  238. }
  239. });
  240. }
  241.  
  242. /**
  243. * 从服务器上下载文件保存到系统磁盘上
  244. *
  245. * @param saveLocation
  246. *            下载的文件保存路径
  247. * @param downloadBtn
  248. *            触发下载操作的控件按钮,用于设置下载进度情况
  249. */
  250. public void downloadFile(String saveLocation, final Button downloadBtn) {
  251. httpUtils.download(url, saveLocation + filename,
  252. new RequestCallBack<File>() {
  253.  
  254. @Override
  255. public void onStart() {
  256. downloadBtn.setText("连接服务器中...");
  257. }
  258.  
  259. @Override
  260. public void onLoading(long total, long current,
  261. boolean isUploading) {
  262. DecimalFormat df = new DecimalFormat("#.##");
  263. downloadBtn.setText("下载中... "
  264. + df.format((double) current / 1024 / 1024)
  265. + "MB/"
  266. + df.format((double) total / 1024 / 1024)
  267. + "MB");
  268. }
  269.  
  270. @Override
  271. public void onSuccess(ResponseInfo<File> arg0) {
  272. downloadBtn.setText("打开文件");
  273. CommonToast.showLongToastMessage(context, "下载成功!文件("
  274. + arg0.result.getAbsolutePath()
  275. + ")保存在内部存储的Educ文件夹下。");
  276. }
  277.  
  278. @Override
  279. public void onFailure(HttpException arg0, String arg1) {
  280. progressDialog.dismiss();
  281. arg0.printStackTrace();
  282. CommonToast.showShortToastMessage(context, "下载失败,请重试!");
  283. downloadBtn.setText("下载附件");
  284. }
  285. });
  286. }
  287.  
  288. /**
  289. * 从服务器上下载文件保存到系统磁盘上,此方法会弹出进度对话框显示下载进度信息(
  290. * 有的需要知道文件是否下载完成,如果下载完成返回的是改文件在磁盘中的完整路径)
  291. *
  292. * @param saveLocation
  293. *            下载的文件保存路径
  294. */
  295. public void downloadFile(String saveLocation) {
  296. progressDialog.setTitle("下载中,请稍等...");
  297. progressDialog.setCancelable(false);
  298. progressDialog.setCanceledOnTouchOutside(false);
  299. // 设置进度条风格,风格为水平进度条
  300. progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  301. // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
  302. progressDialog.setIndeterminate(false);
  303. httpUtils.download(url, saveLocation + filename,
  304. new RequestCallBack<File>() {
  305.  
  306. @Override
  307. public void onStart() {
  308. progressDialog.show();
  309. }
  310.  
  311. @Override
  312. public void onLoading(long total, long current,
  313. boolean isUploading) {
  314. progressDialog.setProgress((int) current);
  315. progressDialog.setMax((int) total);
  316. }
  317.  
  318. @Override
  319. public void onSuccess(ResponseInfo<File> arg0) {
  320. progressDialog.dismiss();
  321. CommonToast.showLongToastMessage(context, "下载成功!文件("
  322. + arg0.result.getAbsolutePath()
  323. + ")保存在内部存储的Educ文件夹下。");
  324. if (handler != null) {
  325. Message msg = Message.obtain();
  326. msg.obj = arg0.result.getAbsoluteFile();
  327. handler.sendMessage(msg);
  328. }
  329. }
  330.  
  331. @Override
  332. public void onFailure(HttpException arg0, String arg1) {
  333. progressDialog.dismiss();
  334. arg0.printStackTrace();
  335. CommonToast.showShortToastMessage(context, "下载失败,请重试!");
  336. }
  337. });
  338. }
  339.  
  340. }
  341.  
  342. /**
  343. * 单例模式获取HttpUtils对象
  344. *
  345. * @author Shyky
  346. * @date 2014-11-19
  347. */
  348. class XutilsHttpClient {
  349.  
  350. private static HttpUtils client;
  351.  
  352. /**
  353. * 单例模式获取实例对象
  354. *
  355. * @param context
  356. *            应用程序上下文
  357. * @return HttpUtils对象实例
  358. */
  359. public synchronized static HttpUtils getInstence(Context context) {
  360. if (client == null) {
  361. // 设置请求超时时间为10秒
  362. client = new HttpUtils(1000 * 10);
  363. client.configSoTimeout(1000 * 10);
  364. client.configResponseTextCharset("UTF-8");
  365. // 保存服务器端(Session)的Cookie
  366. PreferencesCookieStore cookieStore = new PreferencesCookieStore(
  367. context);
  368. cookieStore.clear(); // 清除原来的cookie
  369. client.configCookieStore(cookieStore);
  370. }
  371. return client;
  372. }
  373.  
  374. }

你可能感兴趣的:(xUtils封装http各种操作)