模拟下Android的请求SpringBoot的数据接口
- 1. 创建SpringBoot项目
- 2. 创建 Android项目
- 3. 结果
1. 创建SpringBoot项目
在 pom.xml 加入
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version>
</dependency>
import lombok.*;@Data
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;private String name;
}
import com.alibaba.fastjson.JSON;
import com.example.demo.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;@RestController
public class UserController {
@GetMapping("/getUserInfo")public String getUserInfo(){
List<User> userList = new ArrayList<>();User user = User.builder().id(1).name("hello").build();User user1 = User.builder().id(2).name("world").build();userList.add(user);userList.add(user1);return JSON.toJSONString(userList);}
}
2. 创建 Android项目
网络权限
<uses-permission android:name="android.permission.INTERNET" />
添加网络配置
manifests application
android:networkSecurityConfig="@xml/network_security_config"
res\xml\network-security-confy.xml
<network-security-config><base-config cleartextTrafficPermitted="true" />
</network-security-config>
引入依赖
// https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttpimplementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.1'
// https://mvnrepository.com/artifact/org.projectlombok/lombokimplementation group: 'org.projectlombok', name: 'lombok', version: '1.18.20'annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.20'
// https://mvnrepository.com/artifact/com.alibaba/fastjsonimplementation group: 'com.alibaba', name: 'fastjson', version: '1.2.76'
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;@Data
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;private String name;
}
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.chsengni.myapplication.pojo.User;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class HttpUtil {
private final static int SUCCESS = 1;private final static int FAIL = 0;private static Context AppContext;public static void GetRequest(Context context, String url){
AppContext = context;Thread thread = new Thread(){
@Overridepublic void run() {
getResponseBody(url);super.run();}};thread.start();}public static void getResponseBody(String url){
final Message msg = handler.obtainMessage();OkHttpClient okHttpClient = new OkHttpClient();String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36";Bundle bundle = new Bundle();Request okRequest = new Request.Builder().url(url).addHeader("User-Agent",userAgent).build();okHttpClient.newCall(okRequest).enqueue(new Callback() {
@Overridepublic void onFailure(@NotNull Call call, @NotNull IOException e) {
msg.what = FAIL;String error = e.getMessage();bundle.putString("error",error);msg.setData(bundle);handler.sendMessage(msg);}@Overridepublic void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
msg.what = SUCCESS;String data = response.body().string();bundle.putString("data",data);msg.setData(bundle);handler.sendMessage(msg);}});}@SuppressLint("HandlerLeak")public static Handler handler = new Handler() {
@Overridepublic void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:String response = msg.getData().getString("data");List<User> userList = JSON.parseArray(response, User.class);for (User user:userList) {
Toast.makeText(AppContext, "ID="+ user.getId() +" Name="+user.getName(), Toast.LENGTH_LONG).show();}break;case FAIL:Toast.makeText(AppContext, msg.getData().getString("error"),Toast.LENGTH_LONG).show();break;default:super.handleMessage(msg);}}};
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;public class MainActivity extends AppCompatActivity {
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);HttpUtil.GetRequest(getApplicationContext(),"http://192.168.3.101:8080/getUserInfo");}
}
192.168.3.101 局域网IP
3. 结果