一,概述
okhttp的简单使用主要包含:
- 一般的get请求
- 一般的post请求
- 基于Http的文件上传
- 文件下载
- 加载图片
- 支持请求回调,直接返回对象,对象集合
- 支持session的保持
对于Android Stydio的用户,可以选择添加:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
okHttp3的API http://square.github.io/okhttp/3.x/okhttp/
二,使用教程
1,HttpGet
public void HttpGet(){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
Call call = client.newCall(request);
//加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
String html = response.body().string();
Log.d("html",html);
}
});
}
在Request中,我们可以通过Request.Builder设置更多的参数,像head,method等
然后通过request的对象去构造一个Call对象,类似于将我们的请求封装成任务,既然是任务,就会有execute()和cancle()等方法
A call is a request that has been prepared for execution. A call can be canceled. As this object represents a single request/response pair (stream), it cannot be executed twice.
如果希望用异步的方法去执行请求,我们就调用call.enqueue,将call加入调度队列,然后等待任务执行完成,我们就可以在CallBack中得到结果
如果不想用异步,我们可以这样:
try{
Response response = call.execute();
String html = response.body().string();
}catch (IOException e){
e.printStackTrace();
}
execute() Invokes the request immediately, and blocks until the
response can be processed or is in error.
它会马上执行,阻塞其他的,直到有了repsonse或者错误
我们看到返回的response,一般情况下,如果我们想要得到返回的字符串,可以通过response.body().string
获取,如果希望获取返回的二进制数组,我们可以通过response.body().bytes()
,如果我们想得到inputStream,可以用response.body().byteStream()
这样,我们就可以通过得到inputStream,然后通过IO流来写文件
注意,在异步方法中onResponse执行的线程不是UI线程
2,HttpPost
post Json数据:
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
post 提交键值对:
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody formBody = new FormEncodingBuilder()
//现在一般用FormBody FormBudy.Builder
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
基于Http的文件上传
File file = new File(Environment.getExternalStorageDirectory(), "balabala.mp4");
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(Headers.of( "Content-Disposition",
"form-data; name= username"),RequestBody.create(null,"vivian"))
.addPart(Headers.of("Content-Disposition",
" form-data; name=\"mFile\";"+
"filename=\"wjd.mp4\""), fileBody)
.build();
Request request = new Request.Builder()
.url("http://192.168.1.103:8080/okHttpServer/fileUpload")
.post(requestBody)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
//...
});
上面代码,我们post的时候都用到了RequestBody。
通过查API,RequestBody是一个抽象类,它有两个子类,是FormBody, MultipartBody,而MultipartBody又继承于FormBody,MultipartBody兼容RFC 2387
我们看到RequestBody.create()这个方法,这个是RequestBody内部实现的一个静态方法,返回一个RequestBody对象
我们又看到我在这里用的是new FormEncodingBuilder()这个,可是在OkHttp3中已经去掉了,用的是FormBody, MultipartBody。
封装
public static void getData(String url, final CallBack callBack){
Request request = new Request.Builder()
.url(url)
.build();
Call call = mClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.erro(call,e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callBack.Response(call,response);
}
}
);
}
CallBack是自己定义的接口
整合Gson
OkHttpManager.getData(url, new OkHttpManager.CallBack() {
@Override
public void erro(Call call, Exception e) {
e.printStackTrace();
}
@Override
public void Response(Call call, Response response) {
try {
String s = response.body().string();
Gson gson = new Gson();
User user = gson.fromJson(s,User.class);
}catch (IOException e){
e.printStackTrace();
}
}
});
参考:http://blog.csdn.net/lmj623565791/article/details/47911083
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html