OKHttp get post使用 以及配合gson使用(转ArrayList<T>的方法)

OKHttp

官网地址https://square.github.io/okhttp/

简介

0KHttp是一款高效的HTTP客户端,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的GZIP压缩,请求缓存等优势,其核心主要有路由、连接协议、拦截器、代理、安全性认证、连接池以及网络适配,拦截器主要是指添加,移除或者转换请求或者回应的头部信息

这个库也是square开源的一个网络请求库(okhttp内部依赖okio)。现在已被Google使用在Android源码上了,可见其强大。

关于网络请求库,现在应该还有很多人在使用androi d-async-http。他内部使用的是HttpClient,但是Google在6.0版本里面删除了httpClient 相关API,可见这个库现在有点过时了。

OKHttp主要功能

1、联网请求文本数据
2、大文件下载
3、大文件.上传
4、请求图片

使用

在build.gradle中添加依赖

 implementation "com.squareup.okhttp3:okhttp:4.9.0"

在AndroidManifest.xml中配置联网权限

 <uses-permission android:name="android.permission.INTERNET"/>

在这里插入图片描述

get请求

在官网文档中可看到Get a URL模块里有这么一段代码

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

这就是get方式访问url的方法 直接复制到自己的代码里即可
注意该方法只能在子线程使用 在主线程使用会直接崩!
需要再创建一个子线程调用该GET方法

  MyHandler myHandler = new MyHandler();
        mBtnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            String myURL = get("https://v0.yiketianqi.com/api?version=v61&appid=56962523&appsecret=1aNInold");
                            Message msg = Message.obtain();
                            msg.what = 1;
                            msg.obj = myURL;
                            myHandler.sendMessage(msg);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

通过get获取到url的数据
在这里插入图片描述

POST请求

同样是官方文档内容

public static final MediaType JSON
    = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

同样需要创建子线程 使用post(URL,json)方法 json可以为空"";

   new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    String myURL = post("https://v0.yiketianqi.com/api?version=v61&appid=56962523&appsecret=1aNInold", "");
                    Message msg = Message.obtain();
                    msg.what = 2;
                    msg.obj = myURL;
                    myHandler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

也能同样获取到数据

注意 以上两个方法都是同步处理是用的是execute()

 try (Response response = client.newCall(request).execute()) {
    return response.body().string();

异步处理

要使用enqueue方法 重写Callback()

   client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //如果请求失败
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
				//response请求到的数据
            }
        });

GSON

首先在build.gradle注入依赖(可在github查最新版本https://github.com/google/gson):

implementation 'com.google.code.gson:gson:2.8.6'

在handler的接受数据方法(handleMessage)中创建Gson对象
然后将接受到的json格式数据转化并接收成数据类的对象

Gson gson = new Gson();
WeatherData weatherData = gson.fromJson(data, WeatherData.class);

当要把一个ArrayList类型时

ArrayList<WeatherData> receiveData = gson.fromJson(mMmkv.decodeString("datalist"),  new TypeToken<ArrayList<WeatherData>>() {}.getType());
            

其他更多场景下Gson的使用方法:点击此处跳转

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值