轉自:http://www.gbtags.com/gb/mobileshare/4360.htm
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.shyky.educ.R;
import com.shyky.educ.common.Configs;
import com.shyky.educ.common.Constants;
import com.shyky.educ.dialog.CommonAlertDialog;
import com.shyky.educ.dialog.CommonLoadingDialog;
import com.shyky.educ.view.CommonToast;
/**
* 快速開發框架XUtils幫助類,此類封裝了該框架的各種操作
*
* @author Shyky
* @date 2014-11-19
*/
public class XUtilsHelper {
private Context context;
private Handler handler;
private String url;
/**
* 返回文本的編碼, 默認編碼UTF-8
*/
private HttpUtils httpUtils;
private CommonLoadingDialog loadingDialog;
private CommonAlertDialog alertDialog;
private ProgressDialog progressDialog;
/**
* 請求參數,默認編碼UTF-8
*/
private RequestParams params;
private String filename;
/**
* 構造方法
*
* @param context
* 用於程序上下文,必須用當前Activity的this對象,否則報錯
* @param url
* 網絡資源地址
* @param handler
* 消息處理對象,用於請求完成後的怎麼處理返回的結果數據
*/
public XUtilsHelper(Context context, String url, Handler handler) {
this.context = context;
try {
// 保存網絡資源文件名,要在轉碼之前保存,否則是亂碼
filename = url.substring(url.lastIndexOf("/") + 1, url.length());
// 解決中文亂碼問題,地址中有中文字符造成亂碼問題
String old_url = URLEncoder.encode(url, "GBK");
// 替換地址中的特殊字符
String new_url = old_url.replace("%3A", ":").replace("%2F", "/")
.replace("%3F", "?").replace("%3D", "=")
.replace("%26", "&").replace("%2C", ",")
.replace("%20", " ").replace("+", "%20")
.replace("%2B", "+").replace("%23", "#")
.replace("#", "%23");
this.url = new_url;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.httpUtils = XutilsHttpClient.getInstence(context);
this.handler = handler;
this.loadingDialog = new CommonLoadingDialog(context,
R.layout.activity_input_loading);
this.progressDialog = new ProgressDialog(context);
this.alertDialog = new CommonAlertDialog(context);
this.params = new RequestParams("GBK"); // 編碼與服務器端字符編碼一致爲gbk
}
public void sendGet() {
httpUtils.send(HttpRequest.HttpMethod.GET, url,
new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
}
});
}
/**
* POST請求時需要設置提交參數,解決了中文亂碼設置了字符編碼爲GBK
*
* @param namevlues
* 提交參數/值字符串二維數組
*/
public void setRequestParams(String[][] namevlues) {
for (int i = 0; i < namevlues.length; i++)
params.addBodyParameter(namevlues[i][0], namevlues[i][1]);
}
/**
* POST方式請求服務器資源
*
* @param dialogTitle
* 加載中對話框顯示標題文字
* @param dialogNotingTitle
* 提示對話框標題文字
*/
public void sendPost(final String dialogTitle,
final String dialogNotingTitle) {
if (dialogTitle != null) {
loadingDialog.showDialog(dialogTitle, R.style.loading_dialog,
R.anim.loading, false);
}
httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> arg0) {
Message msg = Message.obtain();
if (arg0.statusCode == 200) {
// 無數據判斷
if (Configs.HTTP_RESPONSE.trim().equals(
arg0.result.trim())
|| arg0.result.trim().startsWith(
"<response totalRows='0'>".trim())
|| arg0.result.trim().contains(
"<items totalRows='0'>".trim())
|| arg0.result.trim().contains(
"<items totalRows='0'".trim())
|| "<classes/>".trim().equals(
arg0.result.trim())
|| "<classes/>".trim().equals(
arg0.result.trim())
|| "[{\"totalRows\":0}]".trim().equals(
arg0.result.trim())) {
if (dialogTitle != null)
loadingDialog.dismiss();
// 需要判斷是否要顯示模式確認對話框
if (dialogNotingTitle != null) {
alertDialog
.showConfirmDialog(
dialogNotingTitle, "確認",
null, null);
}
msg.obj = Constants.TAG_NOTHING;
} else {
if (dialogTitle != null)
loadingDialog.dismiss();
msg.obj = arg0.result;
}
} else {
if (dialogTitle != null)
loadingDialog.dismiss();
msg.obj = Constants.TAG_FAILURE;
}
handler.sendMessage(msg);
}
@Override
public void onFailure(HttpException arg0, String arg1) {
if (dialogTitle != null)
loadingDialog.dismiss();
arg0.printStackTrace();
Message msg = Message.obtain();
msg.obj = Constants.TAG_FAILURE;
handler.sendMessage(msg);
}
});
}
/**
* 上傳文件到服務器
*
* @param param
* 提交參數名稱
* @param file
* 要上傳的文件對象
*/
public void uploadFile(String param, File file) {
progressDialog.setTitle("上傳文件中,請稍等...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
// 設置進度條風格,風格爲水平進度條
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
params.addBodyParameter(param, file);
httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
new RequestCallBack<String>() {
@Override
public void onStart() {
progressDialog.show();
}
@Override
public void onLoading(long total, long current,
boolean isUploading) {
// 設置ProgressDialog 的進度條是否不明確 false 就是不設置爲不明確
progressDialog.setIndeterminate(false);
progressDialog.setProgress((int) current);
progressDialog.setMax((int) total);
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
System.out.println(arg0.statusCode);
System.out.println(arg0.result);
progressDialog.dismiss();
Message msg = Message.obtain();
msg.obj = arg0.result;
handler.sendMessage(msg);
}
@Override
public void onFailure(HttpException arg0, String arg1) {
progressDialog.dismiss();
arg0.printStackTrace();
Message msg = Message.obtain();
msg.obj = Constants.TAG_FAILURE;
handler.sendMessage(msg);
}
});
}
/**
* 從服務器上下載文件保存到系統磁盤上
*
* @param saveLocation
* 下載的文件保存路徑
* @param downloadBtn
* 觸發下載操作的控件按鈕,用於設置下載進度情況
*/
public void downloadFile(String saveLocation, final Button downloadBtn) {
httpUtils.download(url, saveLocation + filename,
new RequestCallBack<File>() {
@Override
public void onStart() {
downloadBtn.setText("連接服務器中...");
}
@Override
public void onLoading(long total, long current,
boolean isUploading) {
DecimalFormat df = new DecimalFormat("#.##");
downloadBtn.setText("下載中... "
+ df.format((double) current / 1024 / 1024)
+ "MB/"
+ df.format((double) total / 1024 / 1024)
+ "MB");
}
@Override
public void onSuccess(ResponseInfo<File> arg0) {
downloadBtn.setText("打開文件");
CommonToast.showLongToastMessage(context, "下載成功!文件("
+ arg0.result.getAbsolutePath()
+ ")保存在內部存儲的Educ文件夾下。");
}
@Override
public void onFailure(HttpException arg0, String arg1) {
progressDialog.dismiss();
arg0.printStackTrace();
CommonToast.showShortToastMessage(context, "下載失敗,請重試!");
downloadBtn.setText("下載附件");
}
});
}
/**
* 從服務器上下載文件保存到系統磁盤上,此方法會彈出進度對話框顯示下載進度信息(
* 有的需要知道文件是否下載完成,如果下載完成返回的是改文件在磁盤中的完整路徑)
*
* @param saveLocation
* 下載的文件保存路徑
*/
public void downloadFile(String saveLocation) {
progressDialog.setTitle("下載中,請稍等...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
// 設置進度條風格,風格爲水平進度條
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 設置ProgressDialog 的進度條是否不明確 false 就是不設置爲不明確
progressDialog.setIndeterminate(false);
httpUtils.download(url, saveLocation + filename,
new RequestCallBack<File>() {
@Override
public void onStart() {
progressDialog.show();
}
@Override
public void onLoading(long total, long current,
boolean isUploading) {
progressDialog.setProgress((int) current);
progressDialog.setMax((int) total);
}
@Override
public void onSuccess(ResponseInfo<File> arg0) {
progressDialog.dismiss();
CommonToast.showLongToastMessage(context, "下載成功!文件("
+ arg0.result.getAbsolutePath()
+ ")保存在內部存儲的Educ文件夾下。");
if (handler != null) {
Message msg = Message.obtain();
msg.obj = arg0.result.getAbsoluteFile();
handler.sendMessage(msg);
}
}
@Override
public void onFailure(HttpException arg0, String arg1) {
progressDialog.dismiss();
arg0.printStackTrace();
CommonToast.showShortToastMessage(context, "下載失敗,請重試!");
}
});
}
}
/**
* 單例模式獲取HttpUtils對象
*
* @author Shyky
* @date 2014-11-19
*/
class XutilsHttpClient {
private static HttpUtils client;
/**
* 單例模式獲取實例對象
*
* @param context
* 應用程序上下文
* @return HttpUtils對象實例
*/
public synchronized static HttpUtils getInstence(Context context) {
if (client == null) {
// 設置請求超時時間爲10秒
client = new HttpUtils(1000 * 10);
client.configSoTimeout(1000 * 10);
client.configResponseTextCharset("UTF-8");
// 保存服務器端(Session)的Cookie
PreferencesCookieStore cookieStore = new PreferencesCookieStore(
context);
cookieStore.clear(); // 清除原來的cookie
client.configCookieStore(cookieStore);
}
return client;
}
}