返回顶部
首页 > 资讯 > 精选 >Android网络编程,调用API获取网络数据
  • 489
分享到

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

androidokhttpjavaAndroid开发网络编程androidstudio 2023-12-23 18:12:54 489人浏览 薄情痞子
摘要

实现步骤: 阅读api接口使用文档使用okHttp 获取网络数据使用 gson将JSON数据转为数据实体类安装GsonFORMatPlus插件使用glide加载网络图片 build.gradle下导入相关依赖 //数据解析

实现步骤:

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

  • 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" />

注意事项:在手机高版本中,需要在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>
  • 编写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;    }        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);            }        });    }}
  • 最终效果
    在这里插入图片描述

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

--结束END--

本文标题: Android网络编程,调用API获取网络数据

本文链接: https://lsjlt.com/news/551726.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作