概述
OKHttp是一个处理网络请求的框架,其优点有,支持http2,对一台机器的所有请求共享同一个socket。
内置连接池,支持连接复用,减少延迟。通过缓存避免重复的请求,请求失败时自动重试主机的其他ip,自动重定向。
添加依赖
compile 'com.squareup.okhttp3:okhttp:3.8.1'
Get请求
Get方式发送同步请求
OkHttpClient okHttpClient; Request request; okHttpClient = new OkHttpClient(); request = new Request.Builder() .url("http://www.baidu.com")//请求接口,如果需要传参拼接到接口后面,如www.baidu.com?name=zhangsan&sex=18 .build(); final Call call = okHttpClient.newCall(request); new Thread(new Runnable() { @Override public void run() { try { Response response = call.execute();//得到Response 对象 if(response.isSuccessful()){//判断是否响应 Log.d("response ","响应码"+response.code());//返回http协议的响应码 Log.d("response ","返回内容"+response.body().string()); } } catch (IOException e) { e.printStackTrace(); } } });
Get方式发送异步请求
OkHttpClient okHttpClient; Request request; okHttpClient = new OkHttpClient(); request = new Request.Builder() .url("http://www.baidu.com")//请求接口。如果需要传参拼接到接口后面,如www.baidu.com?name=zhangsan&sex=18 .build(); final Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()){//判断是否响应 Log.d("response ","响应码"+response.code());//返回http协议的响应码 Log.d("response ","返回内容"+response.body().string()); } } });
Post请求
FormBody传递键值对参数
FormBody body = new FormBody.Builder() //创建信息主体 .add("name", name) .add("sex", department) .add("possword", post) .add("data", formatter.format(getData())) .build();
RequestBody传递Json或File对象
//传递Json对象 MediaType JSON = MediaType.parse("application/json; charset=utf-8");//指定数据类型为json对象, String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据. RequestBody body = RequestBody.create(JSON, josnStr); //传递File对象 MediaType fileType = MediaType.parse("File/*");//指定数据类型为file对象, File file = new File(path);//file对象 RequestBody body = RequestBody.create(fileType , file );
MultipartBody传递键值对对象和 File对象
MultipartBody multipartBody =new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("groupId",""+Id)//添加键值对参数 .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//添加文件 .build();
Post同步/异步请求
//FormBody传递数据,Post同步请求 OkHttpClient okHttpClient; okHttpClient = new OkHttpClient(); FormBody body = new FormBody.Builder() //创建信息主体 .add("name", name) .add("sex", department) .add("possword", post) .add("data", formatter.format(getData())) .build(); Request requset = new Request.Builder() .url("url") .post(body) .build(); final Call call = okHttpClient.newCall(requset); new Thread(new Runnable() { @Override public void run() { try { Response response = call3.execute();//得到Response 对象 if(response.isSuccessful()){//判断是否响应 Log.d("response ","响应码"+response.code());//返回http协议的响应码 Log.d("response ","返回内容"+response.body().string()); } } catch (IOException e) { e.printStackTrace(); } } }); //RequestBody()传递数据,Post异步请求 OkHttpClient okHttpClient; okHttpClient = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式, String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据. RequestBody body = RequestBody.create(JSON, jsonStr); Request request = new Request.Builder() .url("http://www.baidu.com") .post(body) .build(); final Call call = okHttpClient.newCall(requset); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()){//判断是否响应 Log.d("response ","响应码"+response.code());//返回http协议的响应码 Log.d("response ","返回内容"+response.body().string()); } } });
常规请求概述
通过上述代码,Get或Post请求需要实例化OkHttpClient对象,用Request创建请求和Response发送请求,以及Call调度器接收返回内容。
Call对象有两种模式,call.excute()同步模式,call.enqueue()异步模式。
同步是在主线程操作,所以需要开启子线程操作。异步是CallBack回调回来的Response,是在子线程操作,但是回调的onFailure()和onResponse()依然在子线程中。
respinse.body() 也是在子线程,需要接收到内容,才能调用主线程操作。
注意response.body()只能调用一次,因为是输出流的读操作,而读写操作只接收一次,第二次会返回null。
设置网络超时
OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间 .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间