日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android 三方库okhttp、gson、glide的使用

發(fā)布時間:2025/5/22 Android 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 三方库okhttp、gson、glide的使用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

okhttp

Okhttp是網(wǎng)絡(luò)請求框架。OkHttp主要有Get請求、Post請求等功能。
使用前,需要添加依賴,在當前項目的build.gradle下加入以下代碼:

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

Okhttp的Get請求

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

  • 獲取OkHttpClient對象
  • OkHttpClient okHttpClient = new OkHttpClient();
  • 構(gòu)造Request對象
  • Request request = new Request.Builder().get().url("https://v0.yiketianqi.com/api?version=v62&appid=12646748&appsecret=SLB1jIr8&city=北京").build();
  • 將Request封裝為Call
  • Call call = okHttpClient.newCall(request);
  • 根據(jù)需要調(diào)用同步或者異步請求方法
  • //同步調(diào)用,返回Response,會拋出IO異常 Response response = call.execute();//異步調(diào)用,并設(shè)置回調(diào)函數(shù) 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請求很類似,只需要以下五步:

  • 獲取OkHttpClient對象
  • OkHttpClient okHttpClient = new OkHttpClient();
  • 構(gòu)建FormBody或RequestBody或構(gòu)架我們自己的RequestBody,傳入?yún)?shù)
  • //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()//一定要設(shè)置這句.setType(MultipartBody.FORM).addFormDataPart("username", "admin")//.addFormDataPart("password", "admin")//.addFormDataPart("myfile", "1.png", RequestBody.create(MediaType.parse("application/octet-stream"), file)).build();
  • 構(gòu)建Request,將FormBody作為Post方法的參數(shù)傳入
  • final Request request = new Request.Builder().url("http://www.jianshu.com/").post(formBody).build();
  • 將Request封裝為Call
  • Call call = okHttpClient.newCall(request);
  • 調(diào)用請求,重寫回調(diào)方法
  • 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種類型,一種是直接在內(nèi)存中生成object或array,通過手工指定key來獲取值;另一種是借助javabean來進行映射獲取值。
    使用Gson需要添加依賴,在當前項目的build.gradle下加入以下代碼:

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

    實例:解析天氣預(yù)報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;} }

    最后,結(jié)合okhttp即可解析網(wǎng)絡(luò)獲取的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);//異步調(diào)用,并設(shè)置回調(diào)函數(shù)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庫的優(yōu)點:

    • 加載類型多樣化:Glide 支持 Gif、WebP 等格式的圖片。
    • 生命周期的綁定:圖片請求與頁面生命周期綁定,避免內(nèi)存泄漏。
    • 使用簡單(鏈式調(diào)用),且提供豐富的 Api 功能 (如: 圖片裁剪等功能)。
    • 高效的緩存策略:
  • 支持多種緩存策略 (Memory 和 Disk 圖片緩存)。
  • 根據(jù) ImageView 的大小來加載相應(yīng)大小的圖片尺寸。
  • 內(nèi)存開銷小,默認使用 RGB_565 格式 (3.x 版本)。
  • 使用 BitmapPool 進行 Bitmap 的復(fù)用。
  • 首先,使用glide需要添加依賴,在當前項目的build.gradle下加入以下代碼:

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

    其次,在加載圖片時,若需要網(wǎng)絡(luò)請求或者本地內(nèi)存的訪問,需要在當前項目的AndroidManifest.xml中加入請求權(quán)限代碼:

    //用于網(wǎng)絡(luò)請求<uses-permission android:name="android.permission.INTERNET"/>//它可以監(jiān)聽用戶的連接狀態(tài)并在用戶重新連接到網(wǎng)絡(luò)時重啟之前失敗的請求<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類型的參數(shù)。
    • load()方法中不僅可以傳入圖片地址,還可以傳入圖片文件File,resource,圖片的byte數(shù)組等。
    • into()參數(shù)可以直接寫圖片控件,如需要給其他控件添加背景圖片,則需要:
    .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);

    加載應(yīng)用資源:

    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,那么只有當應(yīng)用程序被殺掉的時候,圖片加載才會停止。
    取消圖片:Glide.with(this).load(url).clear();

    總結(jié)

    以上是生活随笔為你收集整理的Android 三方库okhttp、gson、glide的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。