一、添加依賴
通過AndroidStudio搜索添加okhttp3,也可以手動添加
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
二、layout佈局
就放了兩個button
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:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET"/>
<Button
android:id="@+id/btn_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="POST"/>
</LinearLayout>
三、MainActivity代碼
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_get,btn_post;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_get = findViewById(R.id.btn_get);
btn_get.setOnClickListener(this);
btn_post = findViewById(R.id.btn_post);
btn_post.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_get:
request_get();//發起GET請求
break;
case R.id.btn_post:
request_post();//發起POST請求
break;
default:
break;
}
}
四、異步GET
private void request_get(){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
//.addHeader("User-Agent","xxx")//設置請求頭
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//請求失敗時調用
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if (e instanceof SocketTimeoutException){
Log.e("OkHttp請求超時異常", "onFailure: "+e.toString());
}
if (e instanceof ConnectException){
Log.e("OkHttp請求連接異常", "onFailure: "+e.toString());
}
}
//請求成功時調用
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String res = response.body().string();//返回字符串
//InputStream inputStream = response.body().byteStream();//返回流,比如說用於下載圖片等文件
Log.e("OkHttp GET請求成功", "onFailure: "+res);
}
});
}
五、異步POST
private void request_post(){
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()//創建一個請求體
.add("name","name")
.add("password","123456")
.build();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.post(requestBody) //添加請求體
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String res = response.body().string();
Log.e("OkHttp POST請求成功", "onFailure: "+res);
}
});
}
六、添加網絡權限
在Androidmanifest中使用權限
<uses-permission android:name="android.permission.INTERNET"/>
若是Android 9或以上,還需要在application標籤中加入
android:usesCleartextTraffic="true"