Table of contents
An application may use network functions multiple times, which will cause a lot of code duplication. Usually, we should encapsulate these common network operations into a class and provide a static method. When we want to send network requests, we only need to Simply call this method.
The OkHttp method is used below.
Preparation
First add the following to the dependency library:
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
1. Create the HttpUtil class
The sendOkHttpRequest() method has an okHttp3.Callback parameter, which is a callback interface built into the OkHttp library, and the final result will be called back to okhttp3.Callback.
Create a class named HttpUtil with the following code:
public class HttpUtil {
public static void sendOkHttpRequest(final String address, final okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
}
2. Call and use
Modify the activity_main.xml code as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<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>
Modify the MainActivity code as follows:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
HttpUtil.sendOkHttpRequest("http://www.baidu.com", new okhttp3.Callback(){
@Override
public void onFailure(Call call, IOException e) {
// 这里对异常处理
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 这里得到服务器返回的具体内容
String responseData = response.body().string();
showResponse(responseData);
}
});
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
});
}
}
The effect is as follows: