前言:本篇博客教学大家如何使用okhttp发送同步/异步get请求和同步/异步post请求,这边博主把代码全部亲自测试过了一遍,需要源码的可以在文章最后自行拉取。
目录
一、导入依赖
找到build.gradle文件,在dependencies中添加如下依赖:
XML
implementation 'com.squareup.okhttp3:okhttp:3.5.0'
如图所示:
二、开启外网访问权限
找到AndroidManifest.xml文件,添加如下两行代码:
XML
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
如图所示:
三、发送请求
先定义一个全局变量:
java
private OkHttpClient client = new OkHttpClient();
3.1、发送同步get请求
关键代码:
java
// 发送同步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请求
关键代码:
java
// 发送异步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请求
关键代码:
java
// 发送同步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请求
关键代码:
java
// 构建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
<?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实体类
完整代码:
java
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);
}
});
});
}
}