文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android网络编程,调用API获取网络数据

2023-12-23 18:00

关注

实现步骤:

  1. 阅读API接口使用文档
  2. 使用okhttp 获取网络数据
  3. 使用 gson将json数据转为数据实体类
  4. 安装GsonFormatPlus插件
  5. 使用glide加载网络图片

     //数据解析    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'
 <uses-permission android:name="android.permission.INTERNET" />

注意事项:在手机高版本中,需要在application节点下设置 android:networkSecurityConfig=“@xml/network_security_config”

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>
<?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>
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;            }        }    }}
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;    }        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);        }    }}
<?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>
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);            }        });    }}

来源地址:https://blog.csdn.net/jky_yihuangxing/article/details/133869285

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯