okhttp的callback方法是 void onFailure(Request request, IOException e);void onResponse(Response response) throws IOException; okhttp3 的Callback方法有void onFailure(Call call, IOException e);void onResponse(Call call, Response response) throws IOException;okhttp3对Call做了更简洁的封装,okhttp3 Call是个接口,okhttp的call是个普通class,一定要注意,无论哪个版本,call都不能执行多次,多次执行需要重新创建。
对https支持的不同 okhttp默认调用了getDefaultSSLSocketFactory方法,该方法提供了默认的SSLSocketFactory,就算不设置SSLSocketFactory也可以支持https,setSslSocketFactory没有做非空判断,如果设置为空,则使用默认的SSLSocketFactory。okhttp3设置https的方法sslSocketFactory,对SSLSocketFactory做了非空判断,为空会抛出异常。如果不主动设置SSLSocketFactory,okhttp3也提供了默认的http3支持 if (builder.sslSocketFactory != null || !isTLS) { this.sslSocketFactory = builder.sslSocketFactory; } else { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); this.sslSocketFactory = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } }
OkHttp的基本使用 HTTP GET OkHttpClient client = new OkHttpClient(); String doGet(String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { return ""; //根据自己的需要做异常数据处理 } } Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。 Response类: public boolean isSuccessful() Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted. response.body()返回ResponseBody类
可以方便的获取string public final String string() throws IOException Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8. Throws: IOException 当然也能获取到流的形式: public final InputStream byteStream() HTTP POST POST提交Json数据 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String jsonstr) throws IOException { RequestBody body = RequestBody.create(JSON, jsonstr);
Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); f (response.isSuccessful()) { return response.body().string(); } else { return ""; //根据自己的需要做异常数据处理 } } 使用Request的post方法来提交请求体RequestBody POST提交键值对 很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。
OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody formBody = new FormEncodingBuilder() .add("platform", "android") .add("name", "robert") .add("info", "abcdefg") .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 { return ""; //根据自己的需要做异常数据处理
}
}