Android MVP框架请求接口

本文介绍了如何在Android中使用MVP架构进行网络接口请求。通过添加依赖、网络权限,然后详细讲解了HttpURLConnection工具类、MyCallBack接口、M层、P层以及Activity的实现,包括XML布局、适配器、item布局和bean类的设计,最终完成了一个能够请求接口并显示数据的MVP框架。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MVP采用的一对一,也就是说一个类对应一个接口
一、添加依赖

implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

二、添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

三、主要代码

1>HttpURLConnection网络请求工具类

public class HttpUtils {

    public static String getString(String urls) throws Exception {

        URL url = new URL(urls);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = connection.getInputStream();
        String s = setStream(inputStream);
        return s;
    }

    private static String setStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder builder = new StringBuilder();
        String con = "";
        while ((con = reader.readLine()) != null) {
            builder.append(con);
        }
        return builder.toString();
    }
}

2>MyCallBack接口

public interface MyCallBack<T> {
    //最终的接口回调,网络请求的成功或失败的数据
    void success(T data);
    void error(String error);
}

3>M层的接口

public interface Model {
    void getData(String urls, MyCallBack myCallBack);
}

4>M层对应的类

public class ModelImpl implements Model {

    private MyCallBack myCallBack;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                NewsBean data = (NewsBean) msg.obj;
                myCallBack.success(data
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值