引子:
OkHttp是当下比较流行的网络请求框架之一。易用性,复用性都比较好。一般使用时,最好再对它进行再次封装,以符合具体场景的使用需求。本文主要介绍大概的使用方法。
库的引用:
引入okhttp的库,而且okhttp依赖okio的库,所以两者必须同步引入。
方式1)下载jar包,然后放到工程里(3.3.0是版本号,可以更换的)
okhttp-3.3.0.jar
okio-1.8.0.jar
方式2)Maven依赖(3.3.0是版本号,可以更换的)
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.0</version>
</dependency>
方式3)androidStudio中,直接添加gradle引用;(3.10.0是okhttp库版本号)
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okio:okio:1.8.0'
}
okhttp的同步请求以及异步请求的写法 :
网络请求都有同步异步之分,okhttp也不例外,在okhttp中,两者区别如下:
同步请求会阻塞线程,并且不能运行在UI线程;
异步请求不会阻塞,也可以运行在UI线程,但是必须编写一个Callback;
/**
* 同步请求
*/
private void testSyncOkHttp() throws IOException {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
/**
* 异步请求
*/
private void testAsyncOkHttp() {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url("http://www.publicobject.com/helloworld.txt").get().build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(tag, "onFailure;" + e.getLocalizedMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(tag, "onResponse;" + response.body().string());
}
});
}
Get请求和Post请求(都以同步请求为例)
Get
private void testGetSync() {
String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
如果想要在request中添加header键值对,调用如下代码. header方法可以重复调用
Request request = new Request.Builder()
.header("键","值")
.header("键","值")
.header("键","值")
...
.url(url)
.build();
Post:
可以看到post请求就是将 键值对放在了FormBody中,然后调用Request.Builder()的post方法设置进去.
private void testPostSync() {
String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("键", "值")
.add("键", "值")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
上面的post方式只是其中一种。因为post的表单格式有多种。
常见的3种格式为:
1)application/x-www-form-urlencoded 数据是个普通表单,键值对形式(这种格式,直接使用上面的代码就可以)
2)multipart/form-data 数据里有文件
3) application/json 数据是个json
格式2)的RequestBody构建方式为:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
.build();
格式3)的requestBody构建方式为:
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "你的json");
以上内容只做备忘或者入门者阅读,有更多更复杂的情况,可根据上面的线索自行百度谷歌。