简介
官网
简单示例
0. 引入OkHttp
import okhttp3.*;
1. 创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(9, TimeUnit.SECONDS)
.build();
2. 创建Request
final Request request = new Request.Builder()
.client(okHttpClient)
.url("https://www.baidu.com/")
.build();
3. 创建Call
Call call = okHttpClient.newCall(request);
4. 执行Call
异步执行
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
byte[] bytes = response.body().bytes();
// 用于下载文件,可以参考Android原生HTTP API,注意处理异常。
ByteArrayInputStream inputStream = (ByteArrayInputStream) response.body().byteStream();
runOnUiThread(new Runnable() {
@Override
public void run() {
// 更新UI线程控件
}
});
}
});
同步执行
try {
Response response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
POST示例
1. 创建RequestBody
类型一:FormBody
RequestBody body1 = new FormBody.Builder().add("username", "name").build();
类型二:MultipartBody
File file = new File(Environment.getExternalStorageDirectory(), "balabala.mp4");
RequestBody body2 = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("name1", "value1")
// 上传文件
.addFormDataPart("name2", "filename1", RequestBody.create(MediaType.parse("image/png"), file))
.addPart(Headers.of( "Content-Disposition", "form-data; name=\"name3\""),
RequestBody.create(null, "value2"))
// 上传文件
.addPart(Headers.of("Content-Disposition", "form-data; name=\"name4\"; filename =\"filename2\""),
RequestBody.create(MediaType.parse("image/png"), file))
.build();
2. 创建Request
Request request = new Request.Builder()
.url("https://www.baidu.com/")
.post(/* RequestBody */)
.build();
注意事项
-
baseUrl
必须以/
结尾。 -
onResponse()
在 UI线程 中,可以更新UI。