本文主要是介绍网络下载-xUtils,HttpUtils,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
xUtils有四大模块:数据库DbUtils,控件ViewUtils,网络ViewUtils,图片BitmapUtils
// get 提交
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.GET,"http://www.lidroid.com",new RequestCallBack<String>(){@Overridepublic void onLoading(long total, long current, boolean isUploading) {testTextView.setText(current + "/" + total);}@Overridepublic void onSuccess(ResponseInfo<String> responseInfo) {textView.setText(responseInfo.result);}@Overridepublic void onStart() {}@Overridepublic void onFailure(HttpException error, String msg) {}
});
// Post 提交数据,或者上传文件
RequestParams params = new RequestParams();
params.addHeader("name", "value");
params.addQueryStringParameter("name", "value");
// 只包含字符串参数时默认使用BodyParamsEntity,
// 类似于UrlEncodedFormEntity("application/x-www-form-urlencoded")。
params.addBodyParameter("name", "value");
// 加入文件参数后默认使用MultipartEntity("multipart/form-data"),
// 如需"multipart/related",xUtils中提供的MultipartEntity支持设置subType为"related"。
// 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity(如:
// MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity)。
// 例如发送json参数:params.setBodyEntity(new StringEntity(jsonStr,charset));
params.addBodyParameter("file", new File("path"));
...
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.POST,
"uploadUrl....",
params,
new RequestCallBack<String>() {
@Override
public void onStart() {
testTextView.setText("conn...");
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
if (isUploading) {
testTextView.setText("upload: " + current + "/" + total);
} else {
testTextView.setText("reply: " + current + "/" + total);
}
}
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
testTextView.setText("reply: " + responseInfo.result);
}
@Override
public void onFailure(HttpException error, String msg) {
testTextView.setText(error.getExceptionCode() + ":" + msg);
}
});
// 下载文件
HttpUtils http = new HttpUtils();
HttpHandler handler = http.download("http://apache.dataguru.cn/httpcomponents/httpclient/source/httpcomponents-client-4.2.5-src.zip",
"/sdcard/httpcomponents-client-4.2.5-src.zip",
true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
true, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
new RequestCallBack<File>() {
@Override
public void onStart() {
testTextView.setText("conn...");
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
testTextView.setText(current + "/" + total);
}
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
testTextView.setText("downloaded:" + responseInfo.result.getPath());
}
@Override
public void onFailure(HttpException error, String msg) {
testTextView.setText(msg);
}
});
...
//调用cancel()方法停止下载
handler.cancel();
...
这篇关于网络下载-xUtils,HttpUtils的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!