MVC模式
程序员文章站
2022-03-23 11:28:36
MVC模式一、MVC介绍二、创建Model包public interface GetModel { void getJsonData(OkCallBack okCallBack);}生成构造public class GetModelImpl implements GetModel { @Override public void getJsonData(OkCallBack okCallBack) { OkHttpUtils.getInstance()...
MVC模式
一、MVC介绍
二、创建Model包
public interface GetModel {
void getJsonData(OkCallBack okCallBack);
}
生成构造
public class GetModelImpl implements GetModel {
@Override
public void getJsonData(OkCallBack okCallBack) {
OkHttpUtils.getInstance().doget("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1", okCallBack);
}
}
三、创建OkHttp工具类
public class OkHttpUtils {
private OkHttpClient okHttpClient;
private Handler handler = new Handler();
private OkHttpUtils() {
okHttpClient = new OkHttpClient.Builder()
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.build();
}
private static OkHttpUtils okHttpUtils = new OkHttpUtils();
public static OkHttpUtils getInstance() {
return okHttpUtils;
}
//get请求
public void doget(String url, final OkCallBack okCallBack) {
Request request = new Request.Builder().get().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
okCallBack.onError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String string = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
okCallBack.onOk(string);
}
});
}
});
}
}
创建接口
public interface OkCallBack {
void onError(String message);
void onOk(String json);
}
四、Activity代码
public class MainActivity extends AppCompatActivity {
private Button btnId;
private TextView textId;
private GetModel getModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnId = (Button) findViewById(R.id.btn_id);
textId = (TextView) findViewById(R.id.text_id);
getModel = new GetModelImpl();
btnId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getModel.getJsonData(new OkCallBack() {
@Override
public void onError(String message) {
textId.setText(message + "");
}
@Override
public void onOk(String json) {
textId.setText(json + "");
}
});
}
});
}
}
本文地址:https://blog.csdn.net/Sun_Sees_You/article/details/107372592