前言:本篇博客教学大家如何使用okhttp发送同步/异步get请求和同步/异步post请求,这边博主把代码全部亲自测试过了一遍,需要源码的可以在文章最后自行拉取。
一、导入依赖
找到build.gradle文件,在dependencies中添加如下依赖:
implementation 'com.squareup.okhttp3:okhttp:3.5.0'
如图所示:
二、开启外网访问权限
找到AndroidManifest.xml文件,添加如下两行代码:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
如图所示:
三、发送请求
先定义一个全局变量:
private OkHttpClient client = new OkHttpClient();
3.1、发送同步get请求
关键代码:
// 发送同步GET请求
new Thread(() -> {
Request request = new Request.Builder()
.url("https://www.httpbin.org/get?key=1&value=2")
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
// 处理返回的数据
} catch (IOException e) {
e.printStackTrace();
}
}).start();
运行结果:
3.2、发送异步get请求
关键代码:
// 发送异步GET请求
Request request = new Request.Builder()
.url("https://www.httpbin.org/get?key=1&value=2")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseData = response.body().string();
System.out.println(responseData);
// 处理返回的数据
}
});
运行结果:
3.3、发送同步post请求
关键代码:
// 发送同步POST请求
new Thread(() -> {
RequestBody requestBody = new FormBody.Builder()
// 添加POST请求参数
.add("key","1")
.add("value","2")
.build();
Request request = new Request.Builder()
.url("https://www.httpbin.org/post")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
// 处理返回的数据
} catch (IOException e) {
e.printStackTrace();
}
}).start();
运行结果:
3.4、发送异步post请求
关键代码:
// 构建JSON数据字符串
String json = "{\"key\": \"1\", \"value\": \"2\"}";
// 创建RequestBody
RequestBody requestBody = RequestBody.create(
MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url("https://www.httpbin.org/post")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseData = response.body().string();
System.out.println(responseData);
}
});
运行结果:
四、完整代码
4.1、activity_main.xml页面
完整代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnSyncGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送同步GET请求"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/btnAsyncGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送异步GET请求"
android:layout_below="@id/btnSyncGet"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/btnSyncPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送同步POST请求"
android:layout_below="@id/btnAsyncGet"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/btnAsyncPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送异步POST请求"
android:layout_below="@id/btnSyncPost"
android:layout_marginTop="20dp"/>
</RelativeLayout>
预览截图:
4.2、MainActivity实体类
完整代码:
package com.example.okhttp;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSyncGet = findViewById(R.id.btnSyncGet);
Button btnAsyncGet = findViewById(R.id.btnAsyncGet);
Button btnSyncPost = findViewById(R.id.btnSyncPost);
Button btnAsyncPost = findViewById(R.id.btnAsyncPost);
btnSyncGet.setOnClickListener(v -> {
// 发送同步GET请求
new Thread(() -> {
Request request = new Request.Builder()
.url("https://www.httpbin.org/get?key=1&value=2")
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
// 处理返回的数据
} catch (IOException e) {
e.printStackTrace();
}
}).start();
});
btnAsyncGet.setOnClickListener(v -> {
// 发送异步GET请求
Request request = new Request.Builder()
.url("https://www.httpbin.org/get?key=1&value=2")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseData = response.body().string();
System.out.println(responseData);
// 处理返回的数据
}
});
});
btnSyncPost.setOnClickListener(v -> {
// 发送同步POST请求
new Thread(() -> {
RequestBody requestBody = new FormBody.Builder()
// 添加POST请求参数
.add("key","1")
.add("value","2")
.build();
Request request = new Request.Builder()
.url("https://www.httpbin.org/post")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
// 处理返回的数据
} catch (IOException e) {
e.printStackTrace();
}
}).start();
});
btnAsyncPost.setOnClickListener(v -> {
// 构建JSON数据字符串
String json = "{\"key\": \"1\", \"value\": \"2\"}";
// 创建RequestBody
RequestBody requestBody = RequestBody.create(
MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url("https://www.httpbin.org/post")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseData = response.body().string();
System.out.println(responseData);
}
});
});
}
}
五、Gitee源码
源码自取:Android Studio整合okhttp发送同步/异步get和同步/异步post请求
版权归原作者 黄团团 所有, 如有侵权,请联系我们删除。