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

慈云数据 6个月前 (05-11) 技术支持 68 0

实现步骤:

  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节点下设置
       
      

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

      network_security_config.xml文件如下

      
          
      
      
      • 编写activity_news.xml新闻主页面
        
            
            
        
        
        • 根据网络返回数据编写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 data;
                  private String page;
                  private String pageSize;
                  public String getStat() {
                      return stat;
                  }
                  public void setStat(String stat) {
                      this.stat = stat;
                  }
                  public List getData() {
                      return data;
                  }
                  public void setData(List 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 {
                private List mDataBeanList = new ArrayList();
                private Context mContext;
                public NewsListAdapter(Context context) {
                    this.mContext = context;
                }
                /**
                 * 为adapter 设置数据源
                 */
                public void setListData(List 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 新闻布局文件
              
                  
                      
                      
                          
                          
                          
                      
                  
              
              
              • 新闻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);
                            }
                        });
                    }
                }
                
                • 最终效果

                  在这里插入图片描述

微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon