一个支持Http和Http/2,可适用于Android以及Java应用的网络请求客户端。
Http是现代网络应用的所常用的协议,它是一种数据传输的媒介。执行高效的Http代码可以让应用程序以更快的加载速度以及更少的带宽去请求数据。
OkHttp是一种高效的Http请求客户端,通常情况下它拥有以下特点:
OkHttp可以在请求出现问题时 坚守 灵活处理:针对于常见的连接问题,OkHttp会默认自动帮应用做修复处理。如果你的服务器有多个IP地址,OkHttp将会在请求失败时,不断尝试连接另外的IP地址。当服务器同时支持IPv4
+IPv6
,或者主机服务器出现数据故障时,这是非常有用的。如果握手失败,OkHttp会自动初始化一个带有TLS(SNI, ALPN)
协议的新连接向支持TLS 1.0
的服务器再次发起请求。
OkHttp的用法是非常简单的。OkHttp的请求/响应的Api被设计成建造者模式 ,并且它拥有不变性。它既可以在主线程中调用相应的闭包,也可以在子线程中去回调相应方法。
OkHttp支持Android 2.3以上的版本。对于Java 应用,最小版本需要JDK 1.7以上。
okhttp-3.8.0.jar包下载链接
如果你通过向应用导入Jar包的方式集成,你必须同时集成Okio,Okio为OkHttp提供了快速的I/O操作以及可调整大小的缓存区。
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.8.0</version> </dependency>
compile ‘com.squareup.okhttp3:okhttp:3.8.0‘
下面的代码通过一个URL去下载一个文本,并且打印出文本内容。
public class GetExample { OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } public static void main(String[] args) throws IOException { GetExample example = new GetExample(); String response = example.run("https://raw.github.com/square/okhttp/master/README.md"); System.out.println(response); } }
下面代码展示了向服务器上传数据的操作。
public class PostExample { public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } String bowlingJson(String player1, String player2) { return "{‘winCondition‘:‘HIGH_SCORE‘," + "‘name‘:‘Bowling‘," + "‘round‘:4," + "‘lastSaved‘:1367702411696," + "‘dateStarted‘:1367702378785," + "‘players‘:[" + "{‘name‘:‘" + player1 + "‘,‘history‘:[10,8,6,7,8],‘color‘:-13388315,‘total‘:39}," + "{‘name‘:‘" + player2 + "‘,‘history‘:[6,10,5,10,10],‘color‘:-48060,‘total‘:41}" + "]}"; } public static void main(String[] args) throws IOException { PostExample example = new PostExample(); String json = example.bowlingJson("Jesse", "Jake"); String response = example.post("http://www.roundsapp.com/post", json); System.out.println(response); } }
其他可参考:https://blog.csdn.net/u012124438/article/details/54236967
原文:https://www.cnblogs.com/muxi0407/p/11793736.html