okhttp_utils是对OKHTTP的封装使用。国内大神的倾心力作。
get或post基本使用
OkHttpUtils.initClient(client)
.get()
.url(url)
.build()
.execute(new Callback() {
@Override
public Object parseNetworkResponse(Response response, int id) throws Exception {
return null;
}
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(Object response, int id) {
}
});
下载文件
OkHttpUtils.initClient(client)//
.get()//
.url("https://qd.myapp.com/myapp/qqteam/pcqq/QQ9.0.9_1.exe")//模拟下载QQ文件
.build()//
.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "qq.exe")//文件下载进度回调
{
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(File response, int id) {
Log.e(TAG, "onResponse :" + response.getAbsolutePath());
}
@Override
public void inProgress(float progress, long total, int id) {
mProgressBar.setProgress((int) (100 * progress));
Log.d(TAG, progress+"");
}
});
上传文件(支持多文件上传)
String url="http://localhost:8080/FileUpload/FileUploadServlet";
File file1=new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),"1.jpg");
if(!file1.exists()){检查文件是否存在
Toast.makeText(this,"The file is missing!",Toast.LENGTH_SHORT).show();
}
OkHttpUtils
.initClient(client)
.post()
.addFile("nihao","pic_1.jpg",file1)
.url(url)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(String response, int id) {
}
@Override
public void inProgress(float progress, long total, int id) {
super.inProgress(progress, total, id);
mProgressBar.setProgress((int) (100*progress));
}
});