okhttp

Okhttp是网络请求框架。OkHttp主要有Get请求、Post请求等功能。
使用前,需要添加依赖,在当前项目的build.gradle下加入以下代码:

implementation 'com.squareup.okhttp3:okhttp:3.5.0'

Okhttp的Get请求

使用OkHttp进行Get请求只需要完成以下四步:

  1. 获取OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
  1. 构造Request对象
Request request = new Request.Builder().get().url("https://v0.yiketianqi.com/api?version=v62&appid=12646748&appsecret=SLB1jIr8&city=北京").build();
  1. 将Request封装为Call
Call call = okHttpClient.newCall(request);
  1. 根据需要调用同步或者异步请求方法
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();//异步调用,并设置回调函数
call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Toast.makeText(OkHttpActivity.this, "get failed", Toast.LENGTH_SHORT).show();}@Overridepublic void onResponse(Call call, final Response response) throws IOException {final String res = response.body().string();runOnUiThread(new Runnable() {@Overridepublic void run() {textView.setText(res);}});}
});

OkHttp进行Post请求

使用OkHttp进行Post请求和进行Get请求很类似,只需要以下五步:

  1. 获取OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
  1. 构建FormBody或RequestBody或构架我们自己的RequestBody,传入参数
//OkHttp进行Post请求提交键值对
FormBody formBody = new FormBody.Builder().add("username", "admin").add("password", "admin").build();//OkHttp进行Post请求提交字符串
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}");//OkHttp进行Post请求上传文件
File file = new File(Environment.getExternalStorageDirectory(), "1.png");
if (!file.exists()){Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
}else{RequestBody requestBody2 = RequestBody.create(MediaType.parse("application/octet-stream"), file);
}//OkHttp进行Post请求提交表单
File file = new File(Environment.getExternalStorageDirectory(), "1.png");
if (!file.exists()){Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();return;
}
RequestBody muiltipartBody = new MultipartBody.Builder()//一定要设置这句.setType(MultipartBody.FORM).addFormDataPart("username", "admin")//.addFormDataPart("password", "admin")//.addFormDataPart("myfile", "1.png", RequestBody.create(MediaType.parse("application/octet-stream"), file)).build();
  1. 构建Request,将FormBody作为Post方法的参数传入
final Request request = new Request.Builder().url("http://www.jianshu.com/").post(formBody).build();
  1. 将Request封装为Call
Call call = okHttpClient.newCall(request);
  1. 调用请求,重写回调方法
call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Toast.makeText(OkHttpActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();}@Overridepublic void onResponse(Call call, Response response) throws IOException {final String res = response.body().string();runOnUiThread(new Runnable() {@Overridepublic void run() {textView.setText(res);}});}
});

gson

GSON在解析json的时候,大体上有2种类型,一种是直接在内存中生成object或array,通过手工指定key来获取值;另一种是借助javabean来进行映射获取值。
使用Gson需要添加依赖,在当前项目的build.gradle下加入以下代码:

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

实例:解析天气预报api的json。
首先,需要新建一个实体类,eg:

public class CityWeather {private String city;private String country;private String week;private String wea;@SerializedName("wea_img")private String weaImg;private String tem;private String tem1;private String tem2;private String win;@SerializedName("win_speed")private String winSpeed;@SerializedName("win_meter")private String winMeter;@SerializedName("air_level")private String airLevel;@SerializedName("air_pm25")private String airPm25;@SerializedName("hours")private List<HourWeather> hours;public List<HourWeather> getHourWeatherList() {return hours;}public void setHourWeatherList(List<HourWeather> hourWeatherList) {this.hours = hourWeatherList;}public String getWeaImg() {return weaImg;}public void setWeaImg(String weaImg) {this.weaImg = weaImg;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public String getWeek() {return week;}public void setWeek(String week) {this.week = week;}public String getWea() {return wea;}public void setWea(String wea) {this.wea = wea;}public String getTem() {return tem;}public void setTem(String tem) {this.tem = tem;}public String getTem1() {return tem1;}public void setTem1(String tem1) {this.tem1 = tem1;}public String getTem2() {return tem2;}public void setTem2(String tem2) {this.tem2 = tem2;}public String getWin() {return win;}public void setWin(String win) {this.win = win;}public String getWinSpeed() {return winSpeed;}public void setWinSpeed(String winSpeed) {this.winSpeed = winSpeed;}public String getWinMeter() {return winMeter;}public void setWinMeter(String winMeter) {this.winMeter = winMeter;}public String getAirLevel() {return airLevel;}public void setAirLevel(String airLevel) {this.airLevel = airLevel;}public String getAirPm25() {return airPm25;}public void setAirPm25(String airPm25) {this.airPm25 = airPm25;}}

其次,需要新建一个用于json解析的类

public class WeatherUtil {public static CityWeather getCityWeather(String str) {Gson gson = new Gson();Type listType = new TypeToken<CityWeather>(){}.getType();CityWeather cityWeather = gson.fromJson(str, listType);return cityWeather;}
}

最后,结合okhttp即可解析网络获取的json:

public class WeatherActivity extends AppCompatActivity {private List<HourWeather> hourWeatherList;private TextView mWeather;private TextView mCity;private TextView mTem;private TextView mAirLevel;private TextView mTem1;private TextView mTem2;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.weather_activity);initView();OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().get().url("https://v0.yiketianqi.com/api?version=v62&appid=12646748&appsecret=SLB1jIr8&city=北京").build();Call call = okHttpClient.newCall(request);//异步调用,并设置回调函数call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Toast.makeText(WeatherActivity.this, "get failed", Toast.LENGTH_SHORT).show();}@Overridepublic void onResponse(Call call, final Response response) throws IOException {final String res = response.body().string();runOnUiThread(new Runnable() {@Overridepublic void run() {CityWeather cityWeather = WeatherUtil.getCityWeather(res);mWeather.setText(cityWeather.getWea());mCity.setText(cityWeather.getCity());mTem.setText(cityWeather.getTem());mAirLevel.setText(cityWeather.getAirLevel());mTem1.setText(cityWeather.getTem1());mTem2.setText(cityWeather.getTem2() + "℃");hourWeatherList = cityWeather.getHourWeatherList();int resID = getResources().getIdentifier(cityWeather.getWeaImg() + "_bg" , "mipmap", getPackageName());Glide.with(WeatherActivity.this).asBitmap().load(resID).into(new SimpleTarget<Bitmap>(){@Overridepublic void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {Drawable drawable = new BitmapDrawable(resource);mConstraintLayout.setBackground(drawable);}});}});}});}private void initView() {mWeather = findViewById(R.id.weather);mCity = findViewById(R.id.city);mTem = findViewById(R.id.tem);mAirLevel = findViewById(R.id.air_level);mTem1 = findViewById(R.id.tem1);mTem2 = findViewById(R.id.tem2);}
}

glide

Glide 是一个图片加载库,跟它同类型的库还有 Picasso、Fresco、Universal-Image-Loader 等。
glide库的优点:

  • 加载类型多样化:Glide 支持 Gif、WebP 等格式的图片。
  • 生命周期的绑定:图片请求与页面生命周期绑定,避免内存泄漏。
  • 使用简单(链式调用),且提供丰富的 Api 功能 (如: 图片裁剪等功能)。
  • 高效的缓存策略:
  1. 支持多种缓存策略 (Memory 和 Disk 图片缓存)。
  2. 根据 ImageView 的大小来加载相应大小的图片尺寸。
  3. 内存开销小,默认使用 RGB_565 格式 (3.x 版本)。
  4. 使用 BitmapPool 进行 Bitmap 的复用。

首先,使用glide需要添加依赖,在当前项目的build.gradle下加入以下代码:

implementation 'com.github.bumptech.glide:glide:4.8.0'

其次,在加载图片时,若需要网络请求或者本地内存的访问,需要在当前项目的AndroidManifest.xml中加入请求权限代码:

    //用于网络请求<uses-permission android:name="android.permission.INTERNET"/>//它可以监听用户的连接状态并在用户重新连接到网络时重启之前失败的请求<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>//用于硬盘缓存和读取<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

glide的使用

        Glide.with(MainActivity).load(R.mipmap.image).into(imageView);
  • with()方法可以接收Context、Activity或者Fragment类型的参数。
  • load()方法中不仅可以传入图片地址,还可以传入图片文件File,resource,图片的byte数组等。
  • into()参数可以直接写图片控件,如需要给其他控件添加背景图片,则需要:
.into(new SimpleTarget<Bitmap>(){@Overridepublic void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {Drawable drawable = new BitmapDrawable(resource);mConstraintLayout.setBackground(drawable);}});

加载本地图片:

File file = new File(getExternalCacheDir() + "/image.jpg");
Glide.with(this).load(file).into(imageView);

加载应用资源:

int resource = R.drawable.image;
Glide.with(this).load(resource).into(imageView);

加载二进制流:

byte[] image = getImageBytes();
Glide.with(this).load(image).into(imageView);

加载Uri对象:

Uri imageUri = getImageUri();
Glide.with(this).load(imageUri).into(imageView);

注意with()方法中传入的实例会决定Glide加载图片的生命周期,如果传入的是Activity或者Fragment的实例,那么当这个Activity或Fragment被销毁的时候,图片加载也会停止。如果传入的是ApplicationContext,那么只有当应用程序被杀掉的时候,图片加载才会停止。
取消图片:Glide.with(this).load(url).clear();

Android 三方库okhttp、gson、glide的使用相关推荐

  1. Android 三方库EventBus的使用

    EventBus简述 EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Servic ...

  2. Android 三方库lottie、mmkv的使用

    lottie lottie是Airbnb开源的一个面向 iOS.Android.React Native 的动画库,能实现精美.复杂的动画效果. Android端使用方法 首先,需要在当前项目的bui ...

  3. 2022最新中高级Android面试题目,网络相关+Android三方库的源码分析+数据结构与算法

    前言 最近有些朋友提问,Android QQ空间 换肤实现原理是什么?于是,我决定在这里做一下回答.对这个方面感兴趣的朋友也可以来看下. 手q的换肤机制主要是通过拦截系统resource中的sPrel ...

  4. android 三方_面试官送你一份Android热门三方库源码面试宝典及学习笔记

    前言 众所周知,优秀源码的阅读与理解是最能提升自身功力的途径,如果想要成为一名优秀的Android工程师,那么Android中优秀三方库源码的分析和理解则是必备技能.就拿比较热门的图片加载框架Glid ...

  5. android发布三方库到远程maven仓库详细教程

    前提   为什么突然要使用maven了,jcenter可是google御用三方仓库,难道jcenter不香了吗?没错,jcenter就是不香了.当你升级AndroidStudio版本再次创建项目后发现 ...

  6. Android网络库的比较:OkHTTP,Retrofit和Volley [关闭]

    本文翻译自:Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley [closed] Two-part que ...

  7. Android解析JSON,你真的需要三方库?

    一般情况下,如果服务器返回 JSON 数据,而且你又是做 Android 的,那么你首先想到的可能是GSON,或是fastJson这样的框架.这些框架能够很方便和快速的让我们将 JSON 转换成本地对 ...

  8. 使用Android API最佳实践 Retrofit OKHttp GSON

    点击此处查看原文 写在前面 现在,Android应用程序中集成第三方API已十分流行.应用程序都有自己的网络操作和缓存处理机制,但是大部分比较脆弱,没有针对网络糟糕情况进行优化.感谢Square ln ...

  9. Unbuntu环境编译 Android平台可用ffmpeg(带三方库fdk-aac和lame)

    零.准备 编译环境:Ubuntu16.0.4 NDK版本:android-ndk-r21c-linux-x86_64 ffmpeg版本:4.4.1 fdk-aac: fdk-aac-2.0.2 lam ...

最新文章

  1. 【android】android中activity的生命周期
  2. 华硕fx60vm安装macOS10.13.6和Windows10双系统
  3. golang sync.Mutex 互斥锁 使用实例
  4. InetAddress相关笔记
  5. 用IAR调试程序时直接跳过断点执行后面程序的解决办法
  6. win8: hello gril
  7. linux26内核,Linux26内核对象机制研究.pdf
  8. ps4看b站 f怎么调html5,b站html5,b站怎么切换到HTML5版播放器?
  9. AAAI 2021中的目标检测(详细版with code)
  10. 你需要明白的SQL SERVER书签查找(Bookmark Lookup)
  11. texstudio 使用方法_TeXstudio怎么使用,TeXstudio使用教程解析
  12. 「leetcode」112. 路径总和113. 路径总和II(详解)递归函数究竟什么时候需要返回值,什么时候不要返回值?
  13. 一个厂商网站的SQL安全检测 (啊D、明小子)
  14. 如何使用python合并多个excel文件
  15. 联想售后服务偷换主板
  16. Attach函数的讲解
  17. 吴恩达机器学习______学习笔记记录#八、神经网络---表述
  18. linux系统如何下游戏,海岛纪元干货 在Linux系统下如何畅玩游戏攻略
  19. 618前夜:听8年电商操盘手的“数据运营技巧”
  20. Echarts基本使用(vue实现3D地图)

热门文章

  1. 在WPF中实现平滑滚动
  2. spring boot 修改 jackson string的null为空字符串
  3. UGUI内核大探究(一)EventSystem
  4. [docker]docker压力测试
  5. QT STUDY 模型-视图-控制器
  6. 三张图看遍Linux 性能监控、测试、优化工具
  7. JavaScript 操作 COM 控件
  8. Apache Nutch 1.3 学习笔记十一(页面评分机制 OPIC)
  9. C# 中奇妙的函数 -- 1. ToLookup
  10. 如何在Exchange中处理不能发送的信息?