1.OkHttp主页项目github地址:
https://github.com/square/okhttp
2.编写网络请求代码前的一些小步骤:
1.编辑app/build.gradle文件,在dependencies闭包中添加依赖
implementation'com.squareup.okhttp3:okhttp:3.14.2'

2.在AndroidManifest.xml文件中添加访问网络的权限:
<uses-permission android:name="android.permission.INTERNET" />

3.在app目录的build.gradle目录下添加添加对java8支持
方式1:
compileOptions{
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}方式2:
compileOptions {
targetCompatibility = "8"
sourceCompatibility = "8"
}方式3
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}



4.更改网络安全配置(如果请求的网络是https就无需步骤4和步骤5)
第一步:
在res文件夹下创建一个xml文件夹,
然后创建一个network_security_config.xml文件,
文件内容如下:<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>第二步:
在AndroidManifest.xml文件下的application标签增加以下属性
android:networkSecurityConfig="@xml/network_security_config"


3网络请求的一些常规步骤
一:Get请求
步骤1:创建Request对象Request request = new Request.Builder()
.url("http://www.baidu.com")//通过url()方法来设置目标网络地址
.build();步骤2:创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
步骤 3:使用okhttpclient对象调用newCall()方法来创建Call对象,调用execute()方法发送请求并获取服务器返回的数据(Responce对象)
Response responce = client.newCall(request).execute();
步骤4:通过responce.body()获取响应体,进而再调用其它方法获取返回的具体内容(此处以String为例)
String responceData = responce.body().string();
5.get请求
5-1:GET同步请求
private void loadDataSync(){
new Thread(new Runnable() {
@Override
public void run() {
String url="http://www.baidu.com";
//构建一个网络请求
Request request = new Request.Builder().get().url(url).build();
try {
OkHttpClient okHttpClient = new OkHttpClient();
//执行网络请求获取网络响应结果
Response response = okHttpClient.newCall(request).execute();
//获取响应体字符串
String string = response.body().string();
Log.d(TAG,"loadDataSync"+string);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

运行结果如下图所示:

网友评论