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

打印 上一主题 下一主题

主题 510|帖子 510|积分 1530

实现步骤:

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



  • build.gradle下导入相关依赖
  1.      //数据解析
  2.     implementation 'com.google.code.gson:gson:2.8.9'
  3.     //图片加载
  4.     implementation 'com.github.bumptech.glide:glide:4.16.0'
  5.     //网络请求
  6.     implementation 'com.squareup.okhttp3:okhttp:4.11.0'
复制代码


  • AndroidManifest.xml 加入网络权限和 application节点下设置
  1. <uses-permission android:name="android.permission.INTERNET" />
复制代码
  注意事项:在手机高版本中,需要在application节点下设置 android:networkSecurityConfig=“@xml/network_security_config”
  network_security_config.xml文件如下
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
  3.     <base-config cleartextTrafficPermitted="true" />
  4. </network-security-config>
复制代码


  • 编写activity_news.xml新闻主页面
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"
  4.     xmlns:tools="http://schemas.android.com/tools"
  5.     android:layout_width="match_parent"
  6.     android:orientation="vertical"
  7.     android:layout_height="match_parent"
  8.     tools:context=".NewsActivity">
  9.     <androidx.appcompat.widget.Toolbar
  10.         android:layout_width="match_parent"
  11.         android:layout_height="wrap_content"
  12.         android:background="@color/teal_200"
  13.         app:titleTextColor="@color/white"
  14.         app:title="新闻列表"/>
  15.     <androidx.recyclerview.widget.RecyclerView
  16.         android:id="@+id/recyclerView"
  17.         android:layout_width="match_parent"
  18.         tools:listitem="@layout/new_item"
  19.         app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
  20.         android:layout_height="wrap_content"/>
  21. </androidx.appcompat.widget.LinearLayoutCompat>
复制代码


  • 根据网络返回数据编写NewsInfo实体类
  1. public class NewsInfo {
  2.     private String reason;
  3.     private ResultBean result;
  4.     private Integer error_code;
  5.     public String getReason() {
  6.         return reason;
  7.     }
  8.     public void setReason(String reason) {
  9.         this.reason = reason;
  10.     }
  11.     public ResultBean getResult() {
  12.         return result;
  13.     }
  14.     public void setResult(ResultBean result) {
  15.         this.result = result;
  16.     }
  17.     public Integer getError_code() {
  18.         return error_code;
  19.     }
  20.     public void setError_code(Integer error_code) {
  21.         this.error_code = error_code;
  22.     }
  23.     public static class ResultBean {
  24.         private String stat;
  25.         private List<DataBean> data;
  26.         private String page;
  27.         private String pageSize;
  28.         public String getStat() {
  29.             return stat;
  30.         }
  31.         public void setStat(String stat) {
  32.             this.stat = stat;
  33.         }
  34.         public List<DataBean> getData() {
  35.             return data;
  36.         }
  37.         public void setData(List<DataBean> data) {
  38.             this.data = data;
  39.         }
  40.         public String getPage() {
  41.             return page;
  42.         }
  43.         public void setPage(String page) {
  44.             this.page = page;
  45.         }
  46.         public String getPageSize() {
  47.             return pageSize;
  48.         }
  49.         public void setPageSize(String pageSize) {
  50.             this.pageSize = pageSize;
  51.         }
  52.         public static class DataBean {
  53.             private String uniquekey;
  54.             private String title;
  55.             private String date;
  56.             private String category;
  57.             private String author_name;
  58.             private String url;
  59.             private String thumbnail_pic_s;
  60.             private String is_content;
  61.             private String thumbnail_pic_s02;
  62.             public String getUniquekey() {
  63.                 return uniquekey;
  64.             }
  65.             public void setUniquekey(String uniquekey) {
  66.                 this.uniquekey = uniquekey;
  67.             }
  68.             public String getTitle() {
  69.                 return title;
  70.             }
  71.             public void setTitle(String title) {
  72.                 this.title = title;
  73.             }
  74.             public String getDate() {
  75.                 return date;
  76.             }
  77.             public void setDate(String date) {
  78.                 this.date = date;
  79.             }
  80.             public String getCategory() {
  81.                 return category;
  82.             }
  83.             public void setCategory(String category) {
  84.                 this.category = category;
  85.             }
  86.             public String getAuthor_name() {
  87.                 return author_name;
  88.             }
  89.             public void setAuthor_name(String author_name) {
  90.                 this.author_name = author_name;
  91.             }
  92.             public String getUrl() {
  93.                 return url;
  94.             }
  95.             public void setUrl(String url) {
  96.                 this.url = url;
  97.             }
  98.             public String getThumbnail_pic_s() {
  99.                 return thumbnail_pic_s;
  100.             }
  101.             public void setThumbnail_pic_s(String thumbnail_pic_s) {
  102.                 this.thumbnail_pic_s = thumbnail_pic_s;
  103.             }
  104.             public String getIs_content() {
  105.                 return is_content;
  106.             }
  107.             public void setIs_content(String is_content) {
  108.                 this.is_content = is_content;
  109.             }
  110.             public String getThumbnail_pic_s02() {
  111.                 return thumbnail_pic_s02;
  112.             }
  113.             public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
  114.                 this.thumbnail_pic_s02 = thumbnail_pic_s02;
  115.             }
  116.         }
  117.     }
  118. }
复制代码


  • 创建新闻NewsListAdapter适配器
  1. public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.MyHolder> {
  2.     private List<NewsInfo.ResultBean.DataBean> mDataBeanList = new ArrayList<>();
  3.     private Context mContext;
  4.     public NewsListAdapter(Context context) {
  5.         this.mContext = context;
  6.     }
  7.     /**
  8.      * 为adapter 设置数据源
  9.      */
  10.     public void setListData(List<NewsInfo.ResultBean.DataBean> list) {
  11.         this.mDataBeanList = list;
  12.         //一定要调用
  13.         notifyDataSetChanged();
  14.     }
  15.     @NonNull
  16.     @Override
  17.     public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
  18.         //加载布局文件
  19.         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_item, null);
  20.         return new MyHolder(view);
  21.     }
  22.     @Override
  23.     public void onBindViewHolder(@NonNull MyHolder holder, int position) {
  24.         NewsInfo.ResultBean.DataBean dataBean = mDataBeanList.get(position);
  25.         //设置数据
  26.         holder.author_name.setText(dataBean.getAuthor_name());
  27.         holder.title.setText(dataBean.getTitle());
  28.         holder.date.setText(dataBean.getDate());
  29.         //加载图片
  30.         Glide.with(mContext).load(dataBean.getThumbnail_pic_s()).error(R.mipmap.img_error).into(holder.thumbnail_pic_s);
  31.     }
  32.     @Override
  33.     public int getItemCount() {
  34.         return mDataBeanList.size();
  35.     }
  36.     static class MyHolder extends RecyclerView.ViewHolder {
  37.         ImageView thumbnail_pic_s;
  38.         TextView title;
  39.         TextView author_name;
  40.         TextView date;
  41.         public MyHolder(@NonNull View itemView) {
  42.             super(itemView);
  43.             thumbnail_pic_s = itemView.findViewById(R.id.thumbnail_pic_s);
  44.             title = itemView.findViewById(R.id.title);
  45.             author_name = itemView.findViewById(R.id.author_name);
  46.             date = itemView.findViewById(R.id.date);
  47.         }
  48.     }
  49. }
复制代码


  • 编写new_item.xml 新闻布局文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="wrap_content">
  5.     <androidx.appcompat.widget.LinearLayoutCompat
  6.         android:layout_width="match_parent"
  7.         android:layout_height="wrap_content"
  8.         android:layout_margin="10dp">
  9.         <ImageView
  10.             android:id="@+id/thumbnail_pic_s"
  11.             android:layout_width="90dp"
  12.             android:layout_height="100dp"
  13.             android:scaleType="centerCrop"
  14.             android:src="@mipmap/ic_launcher" />
  15.         <androidx.appcompat.widget.LinearLayoutCompat
  16.             android:layout_width="match_parent"
  17.             android:layout_height="match_parent"
  18.             android:layout_marginLeft="10dp"
  19.             android:orientation="vertical">
  20.             <TextView
  21.                 android:id="@+id/title"
  22.                 android:layout_width="wrap_content"
  23.                 android:layout_height="wrap_content"
  24.                 android:layout_marginTop="10dp"
  25.                 android:text="静音车厢”绝非一劳永逸,考验仍在"
  26.                 android:textColor="#333"
  27.                 android:textSize="16sp"
  28.                 android:singleLine="true"
  29.                 android:textStyle="bold" />
  30.             <TextView
  31.                 android:id="@+id/author_name"
  32.                 android:layout_width="wrap_content"
  33.                 android:layout_height="wrap_content"
  34.                 android:layout_marginTop="10dp"
  35.                 android:text="每日看点快看" />
  36.             <TextView
  37.                 android:id="@+id/date"
  38.                 android:layout_width="wrap_content"
  39.                 android:layout_height="wrap_content"
  40.                 android:layout_marginTop="10dp"
  41.                 android:text="2023-10-17 08:34:00" />
  42.         </androidx.appcompat.widget.LinearLayoutCompat>
  43.     </androidx.appcompat.widget.LinearLayoutCompat>
  44. </androidx.appcompat.widget.LinearLayoutCompat>
复制代码


  • 新闻NewsActivity实现过程
  1. public class NewsActivity extends AppCompatActivity {
  2.     private static String URL = "http://v.juhe.cn/toutiao/index?key=b6527106fa4e66a226b5b923d2a8b711&type=yule";
  3.     private RecyclerView mRecyclerView;
  4.     private NewsListAdapter mNewsListAdapter;
  5.     private Handler mHandler = new Handler(Looper.getMainLooper()) {
  6.         @Override
  7.         public void handleMessage(@NonNull Message msg) {
  8.             if (msg.what == 100) {
  9.                 String data = (String) msg.obj;
  10.                 NewsInfo newsInfo = new Gson().fromJson(data, NewsInfo.class);
  11.                 //刷新适配器
  12.                 if (null!=mNewsListAdapter){
  13.                     mNewsListAdapter.setListData(newsInfo.getResult().getData());
  14.                 }
  15.             }
  16.         }
  17.     };
  18.     @Override
  19.     protected void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.         setContentView(R.layout.activity_news);
  22.         //初始化控件
  23.         mRecyclerView = findViewById(R.id.recyclerView);
  24.         //初始化适配器
  25.         mNewsListAdapter = new NewsListAdapter(NewsActivity.this);
  26.         //绑定适配器
  27.         mRecyclerView.setAdapter(mNewsListAdapter);
  28.         getHttpData();
  29.     }
  30.     private void getHttpData() {
  31.         //创建OkHttpClient对象
  32.         OkHttpClient okHttpClient = new OkHttpClient();
  33.         //构构造Request对象
  34.         Request request = new Request.Builder()
  35.                 .url(URL)
  36.                 .get()
  37.                 .build();
  38.         //通过OkHttpClient和Request对象来构建Call对象
  39.         Call call = okHttpClient.newCall(request);
  40.         //通过Call对象的enqueue(Callback)方法来执行异步请求
  41.         call.enqueue(new Callback() {
  42.             @Override
  43.             public void onFailure(@NonNull Call call, @NonNull IOException e) {
  44.                 Log.d("-------------", "onFailure: "+e.toString());
  45.             }
  46.             @Override
  47.             public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
  48. //                Log.d("--------------", "onResponse: " + response.body().string());
  49.                 String data = response.body().string();
  50.                 Message message = new Message();
  51.                 //指定一个标识符
  52.                 message.what = 100;
  53.                 message.obj = data;
  54.                 mHandler.sendMessage(message);
  55.             }
  56.         });
  57.     }
  58. }
复制代码


  • 最终效果


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

祗疼妳一个

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表