前言
由于Google在Android 6.0版本删除了HttpClient相关API,在网络访问这一块,OKHttp也是流行起来,趁着最近有空,参考个各路大神关于OKHttp的文章,总结一下其使用心得。
OKHttp依赖包链接(https://search.maven.org/remote_content?g=com.squareup.okhttp&a=okhttp&v=LATEST)点击下载
OkHttp内部依赖包okio链接(https://search.maven.org/remote_content?g=com.squareup.okio&a=okio&v=LATEST)点击下载
二、Http Get请求
public void httpGet() {
// 创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
// 创建一个Request
final Request request = new Request.Builder()
.url("http://blog.csdn.net/android_mnbvcxz")
.get()
.build();
// new call
Call call = mOkHttpClient.newCall(request);
// 请求加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(final Response response) throws IOException {
// String htmlStr = response.body().string();
}
});
}
以上就是发送一个get请求的步骤:
1.先构造一个Request对象,参数至少有url,也可以通过Request.Builder设置更多的参数:比如header、mehod等;
2.通过request的对象去构造得到一个Call对象,就是请求封装成了任务,拥有execute()和cancel()等方法;
3.最后以异步的方式去执行请求,所以调用call.enqueue,将call加入调度队列,然后等待任务执行完成,即可在CallBack得到结果。
注意
1.onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过response.body().string()
获取;如果希望获得返回的二进制字节数组,则调用response.body().bytes()
;如果你想拿到返回的inputStream,则调用response.body().byteStream();
2.这里是异步的方式去执行,当然也支持阻塞的方式,上面我们也说了Call有一个
execute()
方法,你也可以直接调用call.execute()
通过返回一个Response
。
二、Http Post携带参数请求
//post提交键值对
public void httpPost() {
// 创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
FormEncodingBuilder builder = new FormEncodingBuilder();
// 构造RequestBody
RequestBody requestBody = builder
.add("username", "用戶名")
.add("password", "密码")
.build();
// 创建一个Request
Request request = new Request.Builder()
.url("http://blog.csdn.net/android_mnbvcxz")
.post(requestBody)
.build();
// 请求加入调度
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(final Response response) throws IOException {
// String htmlStr = response.body().string();
}
});
}
//post提交字符串
public void httpPostString() {
// 创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
// 构造RequestBody
RequestBody requestBody = RequestBody
.create(MediaType.parse("text/plain;chaset=utf-8"),"'username':'用户名','passwored':'密码'");
// 创建一个Request
Request request = new Request.Builder()
.url("http://blog.csdn.net/android_mnbvcxz")
.post(requestBody)
.build();
// 请求加入调度
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(final Response response) throws IOException {
// String htmlStr = response.body().string();
}
});
}
//post提交File
public void httpPostFile() {
//1、 创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//2、构造RequestBody
File file = new File(Environment.getExternalStorageDirectory(),"banner.jpg");
if (!file.exists()) {
Log.e("error_tag", file.getAbsolutePath() + "not exist!");
return;
}
//mime type
RequestBody fileBody=RequestBody.create(MediaType.parse("application/octet-stream"), file);
//3、创建一个Request
Request request = new Request.Builder()
.url("http://blog.csdn.net/android_mnbvcxz").post(fileBody)
.build();
//4、请求加入调度
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(final Response response) throws IOException {
// String htmlStr = response.body().string();
}
});
}
这里的post请求携带参数,也仅仅是Request的构造的不同。
1、在httpPost()方法中,参数是包含在请求体中的;所以我们通过FormEncodingBuilder。添加多个String键值对,然后去构造RequestBody,最后完成我们Request的构造。
2、在httpPostString()的方法里参数是一个字符串,所以不需要FormEncodingBuilder这个构造者模式,只需要使用Requestbody的静态方法create即可。
3、在httpPostFile()方法中只是提交了一个文件,所以和httpPostString()一样,使用使用Requestbody的静态方法create
注意
在使用Requestbody的静态方法create时中的若不清楚文件类型的MediaType,可以查看这篇文章http://blog.csdn.net/android_mnbvcxz/article/details/65441571点击打开链接