网络请求库OkHttp的使用
2016-11-29 本文已影响269人
liut_2016
OkHttp是一个开源的Java的http网络请求库,常用于安卓的APP的网络请求。
- 第一步当然要导入jar包,由于OKhttp依赖okio,必须同时导入,这里可通过
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
直接导入,或在官网下载jar包手动导入。
- 构建
OkHttpClient
对象
一般可直接通过client = new OkHttpClient();
即可,如需使用cache
则要
// 设置缓存目录与缓存大小上限
Cache cache = new Cache(new File("okHttpCache"), 1024 * 1000);
// okhttp3不再以setCache设置缓存而是通过OkHttpClient.Builder来设置了
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.cache(cache);
// 构建客户端对象
OkHttpClient = clientBuilder.build();
- 使用
OKhttp
进行GET请求;
封装Request
对象
Request request = new Request.Builder()
.url(url)
.build();
阻塞式请求,通过client
获取request
的Response
对象
Response response = client.newCall(request).execute(); //阻塞
需要注意的是调用.execute()
方法会阻塞当前线程,会一直阻塞到请求完成。
请求结果已经封装在response
对象内。
if (response.isSuccessful()) {
String content = response.body().string();
System.out.println(content);
}
异步请求:
异步请求可直接通过client
获取
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("call = [" + call + "], response = [" + response + "]");
System.out.println();
if (!response.isSuccessful()) {
throw new IOException("" + response);
}
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
System.out.println(headers.name(i) + ": " + headers.value(i));
}
System.out.println();
System.out.println(response.body().string());
}
});
- 使用
OKhttp
进行application/x-www-form-urlencoded
方式POST请求
封装请求参数
RequestBody formBody = new FormBody.Builder()
.add("param0", "lt")
.add("param1", "lt2")
.build();
阻塞式post请求:
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
System.out.println(response.body().string());
}
非阻塞式,跟get使用方式相似,如下
Request request = new Request.Builder().url(url).post(formBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("非阻塞请求 \n" + response.body().string());
}
});
使用OKhttp
进行application/json
方式POST请求
封装请求参数同上
RequestBody formBody = new FormBody.Builder()
.add("param0", "lt")
.add("param1", "lt2")
.build();
设置MediaType
MediaType mediaType = MediaType.parse("application/json; charset=utf-8")
通过mediatype
和json
格式的请求参数来获取RequestBody
RequestBody body = RequestBody.create(mediaType, json);
然后同上直接请求即可
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
总的来说,就是先封装Request对象,再通过client获取Response或异步处理,POST则需额外的请求参数RequestBody和MediaType的封装。
完整测试代码
package xyz.liut.net.http.okhttp;
import java.io.File;
import java.io.IOException;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* OkHttp test
* Created by liut_ on 2016/10/25.
*/
public class OkHttpTest {
public static final String URL = "http://localhost:8080/WebTest/servlet";
public static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
// public static final MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
private OkHttpClient client;
private OkHttpTest() {
// 设置缓存目录与缓存大小上限
Cache cache = new Cache(new File("okHttpCache"), 1024 * 1000);
// okhttp3不再以setCache设置缓存而是通过OkHttpClient.Builder来设置了
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.cache(cache);
// 构建客户端对象
client = clientBuilder.build();
// client.dispatcher().cancelAll(); // 可以取消全部请求
// client = new OkHttpClient(); //不用缓存
}
void doGet(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
// Response response = client.newCall(request).execute(); //阻塞
// if (response.isSuccessful()) {
// String content = response.body().string();
// System.out.println(content);
// }
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("call = [" + call + "], response = [" + response + "]");
System.out.println();
if (!response.isSuccessful()) {
throw new IOException("" + response);
}
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
System.out.println(headers.name(i) + ": " + headers.value(i));
}
System.out.println();
System.out.println(response.body().string());
}
});
}
/**
* 通过application/json方式post
*
* @param url url
* @param json params
* @throws IOException
*/
void doPostByJson(String url, String json) throws IOException {
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
System.out.println(response.body().string());
}
}
/**
* 通过application/x-www-form-urlencoded
*
* @param url url
* @throws IOException
*/
void doPostByFormData(String url) throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("param0", "lt")
.add("param1", "lt2")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
// Response response = client.newCall(request).execute();
//
// if (response.isSuccessful()) {
// System.out.println(response.body().string());
// }
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("非阻塞请求 \n" + response.body().string());
}
});
}
public static void main(String[] args) throws IOException {
OkHttpTest test = new OkHttpTest();
test.doGet(URL + "?" + "param0=woca¶m1=nihao");
test.doPostByJson(URL, "{\"param0\":\"hehe\"}");
test.doPostByFormData(URL);
}
}