【学习笔记-Android】(十三) 网络篇(三)——OkHttp3框架 + 使用Gson解析json数据

本文详细介绍了如何在Android中使用OkHttp3框架进行网络请求,并结合Gson库解析json数据。内容包括异步和同步GET请求,以及POST请求的两种方式:传递键值对和字符串。每个部分都提供了具体的代码实例,帮助开发者理解和应用。
摘要由CSDN通过智能技术生成

网络篇笔记链接:
一、HttpURLConnection
二、Volley框架 + 使用Gson解析json数据
三、OkHttp3框架 + 使用Gson解析json数据
四、WebView组件
五、Android 9.0以上不能访问网络问题解决方法

===============================================================


提示:Android 9.0 版本之后的网络访问有问题的请看我的另一篇文章。
五、Android 9.0以上不能访问网络问题解决方法


学习使用OkHttp3框架

本文目录:

OkHttp3框架简介:
android网络框架之OKhttp
一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso)

用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient

优势

  • 允许连接到同一个主机地址的所有请求,提高请求效率
  • 共享Socket,减少对服务器的请求次数
  • 通过连接池,减少了请求延迟
  • 缓存响应数据来减少重复的网络请求
  • 减少了对数据流量的消耗
  • 自动处理GZip压缩

功能

  • get,post请求
    • 异步GET/POST请求——异步请求需要在子线程中执行
    • 同步GET/POST请求
  • 文件的上传下载
  • 加载图片(内部会图片大小自动压缩)
  • 支持请求回调,直接返回对象、对象集合
  • 支持session的保持

使用:

使用前先添加gradle依赖

	// https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
    implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.10.0'

    // https://mvnrepository.com/artifact/com.squareup.okio/okio
    implementation group: 'com.squareup.okio', name: 'okio', version: '1.14.0'

一、异步GET请求
使用方法:
1.创建OkHttpClient对象

OkHttpClient okHttpClient = new OkHttpClient();

2.创建请求对象

Request request = new Request.Builder().url("http://www.xxx.com").get().build();

3.创建Call对象,将请求对象request作为参数

Call call = okHttpClient.newCall(request);

4.请求加入调度,调用Call的enqueue(),并重写回调方法。异步请求需要开启子线程,或者使用 runOnUiThread()方法才能将数据更新到主线程

call.enqueue(new Callback(){
   
            //请求成功时的回调方法
            @Override
            public void onFailure(Call call, IOException e) {
   

            }
            //请求失败时的回调方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
   
                
            }
        });

提示:子线程记得start一下,不然子线程不会运行。还有记得开启网络权限。

========================================
实例:获取天气数据(异步GET请求)
请求地址:https://www.apiopen.top/weatherApi?city=广州
在这里插入图片描述

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".WeatherActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:background="#03A9F4"
        android:orientation="vertical"
        android:padding="20dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingBottom="20dp">

            <TextView
                android:id="@+id/tv_city"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="城市"
                android:textColor="#fff"
                android:textSize="40sp" />

            <TextView
                android:id="@+id/tv_low"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="最低温度"
                android:textColor="#fff" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" - " />

            <TextView
                android:id="@+id/tv_high"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="最高温度"
                android:textColor="#fff" />

            <TextView
                android:id="@+id/tv_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="date"
                android:textColor="#fff" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="20dp">

            <TextView
                android:id="@+id/tv_wendu"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="25"
                android:textColor="#fff"
                android:textSize="40sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text=""
                android:textColor="#fff"
                android:textSize="40sp" />

            <TextView
                android:id="@+id/tv_type"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="天气类型"
                android:textColor="#fff"
                android:textSize="40sp" />
        </LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/button"
        android:background="#4CAF50"
        android:textColor="#fff"
        android:textSize="20sp"
        android:layout_margin="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加载数据"/>

    <EditText
        android:id="@+id/editText"
        android:layout_margin="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:lines="10"
        android:gravity="start|top"
        android:background="#2D03A9F4"
        android:hint="请求的原始json数据"
        android:inputType="textMultiLine" />

</LinearLayout>

Weather.java

package com.t.testokhttp3.bean;

import java.util.List;

public class Weather {
   
    /**
     * code : 200
     * msg : 成功!
     * data : {"yesterday":{"date":"29日星期四","high":"高温 34℃","fx":"无持续风向","low":"低温 27℃","fl":"<![CDATA[<3级]]>","type":"雷阵雨"},"city":"广州","aqi":null,"forecast":[{"date":"30日星期五","high":"高温 31℃","fengli":"<![CDATA[<3级]]>","low":"低温 26℃","fengxiang":"无持续风向","type":"中雨"},{"date":"31日星期六","high":"高温 31℃","fengli":"<![CDATA[<3级]]>","low":"低温 25℃","fengxiang":"无持续风向","type":"中雨"},{"date":"1日星期天","high":"高温 30℃","fengli":"<![CDATA[<3级]]>","low":"低温 25℃","fengxiang":"无持续风向","type":"雷阵雨"},{"date":"2日星期一","high":"高温 30℃","fengli":"<![CDATA[<3级]]>","low":"低温 25℃","fengxiang":"无持续风向","type":"中雨"},{"date":"3日星期二","high":"高温 31℃","fengli":"<![CDATA[<3级]]>","low":"低温 25℃","fengxiang":"无持续风向","type":"雷阵雨"}],"ganmao":"各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。","wendu":"29"}
     */

    private int code;
    private String msg;
    private DataBean data;

    public int getCode() {
   
        return code;
    }

    public void setCode(int code) {
   
        this.code = code;
    }

    public String getMsg() {
   
        return msg;
    }

    public void setMsg(String msg) {
   
        this.msg = msg;
    }

    public DataBean getData() {
   
        return data;
    }

    
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值