OkHttp
OkHttp是什么?
OkHttp是Square旗下的开源框架,用于简化Android的网络编程
推荐前提阅读:Android基础——网络编程
OkHttp使用
添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
修改activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="send_request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
修改MainAcitivity:
- 创建OkHttpClient实例
- 创建Request实例添加相关参数(网址、响应时间)
- 将Request传入OkHttpClient的newCall()方法中,并调用execute()方法,返回的Response就是服务器的数据
- 调用Response的body()和string()方法获取字符串
public class MainActivity extends AppCompatActivity {
private TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseText = findViewById(R.id.response_text);
Button sendRequest = findViewById(R.id.send_request);
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithOkHttp();
}
});
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String toString) {
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(toString);
}
});
}
}
如果要调用post()方法,需创建RequestBody对象并传入到Request的post()方法:
RequestBody requestBody=new FormBody.Builder()
.add("username","admin")
.add("password","123456")
.build();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.post(requestBody)
.build();
OkHttp最佳用法
新建OkHttpUtil包装OkHttp,通过enqueue()方法传入okhttp3.Callback,通过回调处理返回结果:
public class OkHttpUtil {
public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request=new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
}
使用时通过onResponse()方法处理请求成功后的返回数据,onFailure()方法处理失败的情况:
OkHttpUtil.sendOkHttpRequest("https://www.baidu.com", new okhttp3.Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String responseData = response.body().string();
}
});