一、出现的背景
提高网络请求性能,为高效而生。
二,使用前准备(以下使用Android Studio开发环境)
(1)添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
(2)Gradle配置相关依赖
compile 'com.squareup.okhttp3:okhttp:3.5.0'
如果不知道版本,也可以在代码仓库中查找,如图:
至此Okhttp框架开发前期准备已经做好。
三、Get请求
public class TestGet {
public static void main(String[] args) throws IOException {
TestGet example = new TestGet();
String response = example.run("https://www.baidu.com");
System.out.println(response);
}
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}