Android访问Spring Boot服务器
项目结构
- activity包中存放Activity类,用于操作界面视图
- service包中存放访问服务器的相关Service类,还定义了ICallBack接口和Service父类
- util包中存放一些工具类
具体实现
CommunicationThread类继承自Thread,重写了其中的run方法。有两个参数,一个是Message类(见下文),封装了Request请求的相关信息,一个是ICallBack接口(见下文),为回调函数。
package com.compuslife.util;
import android.util.Log;
import com.alibaba.fastjson.JSONObject;
import com.compuslife.service.ICallBack;
import java.io.IOException;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* 与服务器通信的线程
* Message 封装了Request的相关信息
* ICallBack 为回调函数接口
*/
public class CommunicationThread extends Thread{
private Message message;
private ICallBack iCallBack;
private static final String TAG = "CommunicationThread";
public CommunicationThread(Message message, ICallBack iCallBack){
this.message = message;
this.iCallBack = iCallBack;
}
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
if (this.message.getMethod() == Method.GET){
Request req = new Request.Builder().url(Const.URL + this.message.getUrl()).get().build();
Response res = client.newCall(req).execute();
String responseJson = res.body().string();
Log.d(TAG, responseJson);
this.iCallBack.callback(JSONObject.parseObject(responseJson));
} else {
FormBody.Builder formBuilder = new