1. 什么是okHttp?
2. 究竟怎么才能使用okHttp框架呢?
一、介绍
1、okHttp就是一款强大的网络请求封装库,我们可以进行二次封装很简单的实现网络请求,文件下载,上传等。。。
2、想要使用okHttp,首先必须引入类库
implementation ‘com.squareup.okhttp3:logging-interceptor:3.3.1’
二、简单的封装post Api接口请求的列子
/**
* @param url
*
*
* @return
* @throws IOException
*/
public static void post(String url, HashMap<String,Object> map, final CallBack<Object> callBack) {
/*请求实体*/
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),new Gson().toJson(map));
/*okHttp*/
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
/*请求动作*/
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
/*异步相应的结果*/
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.onFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) {
InputStream inputStream = response.body().byteStream();
byte[] bytes=new byte[1024*1024];
try {
inputStream.read(bytes);
callBack.onFailure(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
callBack.onFailure(e.getMessage());
}
}
});
}