Android Okhttp使用
简介
android网络框架之OKhttp,一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso)
用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient)
okhttp 简单使用
引入依赖
compile 'com.squareup.okhttp3:okhttp:3.7.0'
compile 'com.squareup.okio:okio:1.12.0'
Android 添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
异步GET请求
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
Request request = new Request.Builder().url("http://www.baidu.com").method("GET",null).build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.请求加入调度,重写回调方法
call.enqueue(new Callback() {
//请求失败执行的方法
@Override
public void onFailure(Call call, IOException e) {
}
//请求成功执行的方法
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
同步GET请求
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
Request request = new Request.Builder().url("http://www.baidu.com").method("GET",null).build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.同步调用会阻塞主线程,这边在子线程进行
new Thread(new Runnable() {
@Override
public void run() {
try {
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
POST请求提交键值对
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.通过new FormBody()调用build方法,创建一个RequestBody,可以用add添加键值对
RequestBody requestBody = new FormBody.Builder().add("name","zhangqilu").add("age","25").build();
//3.创建Request对象,设置URL地址,将RequestBody作为post方法的参数传入
Request request = new Request.Builder().url("url").post(requestBody).build();
//4.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//5.请求加入调度,重写回调方法
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
异步POST请求提交字符串
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");//"类型,字节码"
//字符串
String value = "{username:admin;password:admin}";
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.通过RequestBody.create 创建requestBody对象
RequestBody requestBody =RequestBody.create(mediaType, value);
//3.创建Request对象,设置URL地址,将RequestBody作为post方法的参数传入
Request request = new Request.Builder().url("url").post(requestBody).build();
//4.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//5.请求加入调度,重写回调方法
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});