您的当前位置:首页正文

Android开发网络编程,使用API获取网络数据

2024-11-13 来源:个人技术集锦

1. 实现步骤

2. 开发环境

  1. 开发工具:Androidstudio
  2. 开发语言:Java

  • build.gradle下导入相关依赖
     //数据解析
    implementation 'com.google.code.gson:gson:2.8.9'
    //图片加载
    implementation 'com.github.bumptech.glide:glide:4.16.0'
    //网络请求
    implementation 'com.squareup.okhttp3:okhttp:4.11.0'
  • AndroidManifest.xml 加入网络权限和 application节点下设置
 <uses-permission android:name="android.permission.INTERNET" />

network_security_config.xml文件如下

<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
  • 编写activity_news.xml新闻主页面
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".NewsActivity">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/teal_200"
        app:titleTextColor="@color/white"
        app:title="新闻列表"/>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        tools:listitem="@layout/new_item"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:layout_height="wrap_content"/>

</androidx.appcompat.widget.LinearLayoutCompat>
  • 根据网络返回数据编写NewsInfo实体类
public class NewsInfo {


    private String reason;
    private ResultBean result;
    private Integer error_code;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public ResultBean getResult() {
        return result;
    }

    public void setResult(ResultBean result) {
        this.result = result;
    }

    public Integer getError_code() {
        return error_code;
    }

    public void setError_code(Integer error_code) {
        this.error_code = error_code;
    }

    public static class ResultBean {
        private String stat;
        private List<DataBean> data;
        private String page;
        private String pageSize;

        public String getStat() {
            return stat;
        }

        public void setStat(String stat) {
            this.stat = stat;
        }

        public List<DataBean> getData() {
            return data;
        }

        public void setData(List<DataBean> data) {
            this.data = data;
        }

        public String getPage() {
            return page;
        }

        public void setPage(String page) {
            this.page = page;
        }

        public String getPageSize() {
            return pageSize;
        }

        public void setPageSize(String pageSize) {
            this.pageSize = pageSize;
        }

        public static class DataBean {
            private String uniquekey;
            private String title;
            private String date;
            private String category;
            private String author_name;
            private String url;
            private String thumbnail_pic_s;
            private String is_content;
            private String thumbnail_pic_s02;

            public String getUniquekey() {
                return uniquekey;
            }

            public void setUniquekey(String uniquekey) {
                this.uniquekey = uniquekey;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getCategory() {
                return category;
            }

            public void setCategory(String category) {
                this.category = category;
            }

            public String getAuthor_name() {
                return author_name;
            }

            public void setAuthor_name(String author_name) {
                this.author_name = author_name;
            }

            public String getUrl() {
                return url;
            }

            public void setUrl(String url) {
                this.url = url;
            }

            public String getThumbnail_pic_s() {
                return thumbnail_pic_s;
            }

            public void setThumbnail_pic_s(String thumbnail_pic_s) {
                this.thumbnail_pic_s = thumbnail_pic_s;
            }

            public String getIs_content() {
                return is_content;
            }

            public void setIs_content(String is_content) {
                this.is_content = is_content;
            }

            public String getThumbnail_pic_s02() {
                return thumbnail_pic_s02;
            }

            public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
                this.thumbnail_pic_s02 = thumbnail_pic_s02;
            }
        }
    }
}
  • 创建新闻NewsListAdapter适配器
public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.MyHolder> {
    private List<NewsInfo.ResultBean.DataBean> mDataBeanList = new ArrayList<>();
    private Context mContext;


    public NewsListAdapter(Context context) {
        this.mContext = context;
    }


    /**
     * 为adapter 设置数据源
     */
    public void setListData(List<NewsInfo.ResultBean.DataBean> list) {
        this.mDataBeanList = list;
        //一定要调用
        notifyDataSetChanged();

    }


    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //加载布局文件
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_item, null);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        NewsInfo.ResultBean.DataBean dataBean = mDataBeanList.get(position);

        //设置数据
        holder.author_name.setText(dataBean.getAuthor_name());
        holder.title.setText(dataBean.getTitle());
        holder.date.setText(dataBean.getDate());
        //加载图片
        Glide.with(mContext).load(dataBean.getThumbnail_pic_s()).error(R.mipmap.img_error).into(holder.thumbnail_pic_s);


    }

    @Override
    public int getItemCount() {
        return mDataBeanList.size();
    }

    static class MyHolder extends RecyclerView.ViewHolder {

        ImageView thumbnail_pic_s;
        TextView title;
        TextView author_name;
        TextView date;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            thumbnail_pic_s = itemView.findViewById(R.id.thumbnail_pic_s);
            title = itemView.findViewById(R.id.title);
            author_name = itemView.findViewById(R.id.author_name);
            date = itemView.findViewById(R.id.date);

        }
    }
}
  • 编写new_item.xml 新闻布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">


        <ImageView
            android:id="@+id/thumbnail_pic_s"
            android:layout_width="90dp"
            android:layout_height="100dp"
            android:scaleType="centerCrop"
            android:src="@mipmap/ic_launcher" />


        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:orientation="vertical">


            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="静音车厢”绝非一劳永逸,考验仍在"
                android:textColor="#333"
                android:textSize="16sp"
                android:singleLine="true"
                android:textStyle="bold" />


            <TextView
                android:id="@+id/author_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="每日看点快看" />

            <TextView
                android:id="@+id/date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="2023-10-17 08:34:00" />

        </androidx.appcompat.widget.LinearLayoutCompat>

    </androidx.appcompat.widget.LinearLayoutCompat>


</androidx.appcompat.widget.LinearLayoutCompat>
  • 新闻NewsActivity实现过程
public class NewsActivity extends AppCompatActivity {
    private static String URL = "http://v.juhe.cn/toutiao/index?key=b6527106fa4e66a226b5b923d2a8b711&type=yule";

    private RecyclerView mRecyclerView;
    private NewsListAdapter mNewsListAdapter;


    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 100) {
                String data = (String) msg.obj;
                NewsInfo newsInfo = new Gson().fromJson(data, NewsInfo.class);
                //刷新适配器
                if (null!=mNewsListAdapter){
                    mNewsListAdapter.setListData(newsInfo.getResult().getData());
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        //初始化控件
        mRecyclerView = findViewById(R.id.recyclerView);
        //初始化适配器
        mNewsListAdapter = new NewsListAdapter(NewsActivity.this);
        //绑定适配器
        mRecyclerView.setAdapter(mNewsListAdapter);
        getHttpData();
    }

    private void getHttpData() {
        //创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //构构造Request对象
        Request request = new Request.Builder()
                .url(URL)
                .get()
                .build();
        //通过OkHttpClient和Request对象来构建Call对象
        Call call = okHttpClient.newCall(request);
        //通过Call对象的enqueue(Callback)方法来执行异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d("-------------", "onFailure: "+e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                Log.d("--------------", "onResponse: " + response.body().string());
                String data = response.body().string();
                Message message = new Message();
                //指定一个标识符
                message.what = 100;
                message.obj = data;
                mHandler.sendMessage(message);
            }
        });
    }
}

3. 运行效果图

4.视频教程

  1. 视频教程: https://www.bilibili.com/video/BV1Qp4y1T76S/?vd_source=984bb03f768809c7d33f20179343d8c8
显示全文