===
OKHttp主要功能
1、联网请求文本数据
2、大文件下载
3、大文件上传
4、请求图片
get请求
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
post请求
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
第三方封装好的OKHttp库-okhttp-utils
get请求
url="http://api.m.mtime.cn/PageSubArea/TrailerList.api";
OkHttpUtils
.get()
.url(url)
.id(100)
.build()
.execute(new MyStringCallback());
post请求
url="http://api.m.mtime.cn/PageSubArea/TrailerList.api";
OkHttpUtils
.post()
.url(url)
.id(100)
.build()
.execute(new MyStringCallback());
okhttp-utils文件下载
String url = "http://vfx.mtime.cn/Video/2016/07/24/mp4/160724154733643806.mp4";
OkHttpUtils//
.get()//
.url(url)//
.build()//
.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(),
"160724154733643806.mp4")//
{
@Override
public void onBefore(Request request, int id) {
}
@Override
public void inProgress(float progress, long total, int id) {
mProgressBar.setProgress((int) (100 * progress));
Log.e(TAG, "inProgress
:" + (int) (100 * progress));
}
@Override
public void onError(Call call, Exception e, int id) {
Log.e(TAG, "onError :"
+ e.getMessage());
}
@Override
public void onResponse(File file, int id) {
Log.e(TAG, "onResponse
:" + file.getAbsolutePath());
}
});
文件上传
public void multiFileUpload()
{
String mBaseUrl = "http://192.168.10.165:8080/FileUpload/FileUploadServlet";
File file = new File(Environment.getExternalStorageDirectory(),
"1.jpg");
File file2 = new File(Environment.getExternalStorageDirectory(),
"1.txt");
if (!file.exists())
{
Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
return;
}
Map<String, String> params = new HashMap<>();
params.put("username", "杨光福");
params.put("password", "123");
String url = mBaseUrl;
OkHttpUtils.post()//
.addFile("mFile", "messenger_01.png", file)//
.addFile("mFile", "test1.txt", file2)//
.url(url)
.params(params)//
.build()//
.execute(new MyStringCallback());
}
====
rxjava retrofit okhttp
get请求
@GET("text.from?key=ae240f7fba620fc370b803566654949e")