教你分分鐘使用Retrofit+Rxjava實現網絡請求

擼代碼之前,先簡單了解一下為什么Retrofit這么受大家青睞吧。

Retrofit是Square公司出品的基于OkHttp封裝的一套RESTful(目前流行的一套api設計的風格)網絡請求框架。它內部使用了大量的設計模式,以達到高度解耦的目的;它可以直接通過注解的方式配置請求;可以使用不同的Http客戶端;還可以使用json Converter序列化數據,直接轉換成你期望生成的實體bean;它還支持Rxjava等等等(此處省略一萬字...........)

好了,接下來開始我們就開始上代碼,寫個小Demo測試一下它的使用吧! 使用步驟: 1、app的build文件中加入:

//only Retrofit(只用Retrofit聯網)compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0'
//Rxjava and Retrofit(Retrofit+Rx需要添加的依賴)compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'compile 'io.reactivex:rxandroid:1.2.1'compile 'io.reactivex:rxjava:1.2.1'
復制代碼

2、接下來就要編寫實現retrofit聯網的代碼了,以Get請求為例,示例接口:(http://wthrcdn.etouch.cn/weather_mini?city=北京) 首先,你需要創建一個interface用來配置網絡請求。 寫法《一》:單純使用Retrofit,不加Rxjava的使用

/**
* 描述:第一步:定義一個接口配置網絡請求
*/
public interface WeatherService {
//  網絡接口的使用為查詢天氣的接口
//  @GET("weather_mini")
//  此處回調返回的可為任意類型Call<T>,再也不用自己去解析json數據啦!!!Call<WeatherEntity> getMessage(@Query("city") String city);
復制代碼

在需要請求網絡的地方直接調用下面的方法即可:

  /*** 單純使用Retrofit的聯網請求*/private void doRequestByRetrofit() {Retrofit retrofit = new Retrofit.Builder().baseUrl(API.BASE_URL)//基礎URL 建議以 / 結尾.addConverterFactory(GsonConverterFactory.create())//設置 Json 轉換器.build();WeatherService weatherService = retrofit.create(WeatherService .class);Call<WeatherEntity> call = weatherService.getMessage("北京");call.enqueue(new Callback<WeatherEntity>() {@Overridepublic void onResponse(Call<WeatherEntity> call, Response<WeatherEntity> response) {//測試數據返回WeatherEntity weatherEntity = response.body();Log.e("TAG", "response == " +  weatherEntity.getData().getGanmao());}@Overridepublic void onFailure(Call<WeatherEntity> call, Throwable t) {Log.e("TAG", "Throwable : " + t);}});}復制代碼

寫法《二》 Retrofit + Rxjava 區別:使用Rxjava后,返回的不是Call而是一個Observable的對象了。

public interface RxWeatherService {@GET("weather_mini")Observable<WeatherEntity> getMessage(@Query("city") String city);
}
復制代碼

請求聯網代碼:

 private void doRequestByRxRetrofit() {Retrofit retrofit = new Retrofit.Builder().baseUrl(API.BASE_URL)//基礎URL 建議以 / 結尾.addConverterFactory(GsonConverterFactory.create())//設置 Json 轉換器.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava 適配器.build();RxWeatherService rxjavaService = retrofit.create(RxWeatherService .class);rxjavaService .getMessage("北京").subscribeOn(Schedulers.io())//IO線程加載數據.observeOn(AndroidSchedulers.mainThread())//主線程顯示數據.subscribe(new Subscriber<WeatherEntity>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable e) {}@Overridepublic void onNext(WeatherEntity weatherEntity) {Log.e("TAG", "response == " + weatherEntity.getData().getGanmao());}});}
復制代碼

免費贈送一個WeatherEntity實體類(只給偷懶的小伙伴): (在瀏覽器打開http://wthrcdn.etouch.cn/weather_mini?city=北京,取到json串直接用GsonFormat生成即可)

public class WeatherEntity {private DataBean data;private int status;private String desc;public DataBean getData() {return data;}public void setData(DataBean data) {this.data = data;}public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public static class DataBean {private YesterdayBean yesterday;private String city;private String aqi;private String ganmao;private String wendu;private List<ForecastBean> forecast;public YesterdayBean getYesterday() {return yesterday;}public void setYesterday(YesterdayBean yesterday) {this.yesterday = yesterday;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getAqi() {return aqi;}public void setAqi(String aqi) {this.aqi = aqi;}public String getGanmao() {return ganmao;}public void setGanmao(String ganmao) {this.ganmao = ganmao;}public String getWendu() {return wendu;}public void setWendu(String wendu) {this.wendu = wendu;}public List<ForecastBean> getForecast() {return forecast;}public void setForecast(List<ForecastBean> forecast) {this.forecast = forecast;}public static class YesterdayBean {private String date;private String high;private String fx;private String low;private String fl;private String type;public String getDate() {return date;}public void setDate(String date) {this.date = date;}public String getHigh() {return high;}public void setHigh(String high) {this.high = high;}public String getFx() {return fx;}public void setFx(String fx) {this.fx = fx;}public String getLow() {return low;}public void setLow(String low) {this.low = low;}public String getFl() {return fl;}public void setFl(String fl) {this.fl = fl;}public String getType() {return type;}public void setType(String type) {this.type = type;}}public static class ForecastBean {private String date;private String high;private String fengli;private String low;private String fengxiang;private String type;public String getDate() {return date;}public void setDate(String date) {this.date = date;}public String getHigh() {return high;}public void setHigh(String high) {this.high = high;}public String getFengli() {return fengli;}public void setFengli(String fengli) {this.fengli = fengli;}public String getLow() {return low;}public void setLow(String low) {this.low = low;}public String getFengxiang() {return fengxiang;}public void setFengxiang(String fengxiang) {this.fengxiang = fengxiang;}public String getType() {return type;}public void setType(String type) {this.type = type;}}}
}復制代碼

好了,簡單的Retrofit+Rxjava實現聯網到此就完成了。本文主要針對初接觸retrofit的開發童鞋,如果對你有所幫助,不要忘了點個贊哦! 后續會更新Retrofit+Rxjava在實際項目開發中的運用,可以直接拿來在項目中使用噢.......敬請期待??????

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390799.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390799.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390799.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

線程與進程區別

一.定義&#xff1a; 進程&#xff08;process&#xff09;是一塊包含了某些資源的內存區域。操作系統利用進程把它的工作劃分為一些功能單元。 進程中所包含的一個或多個執行單元稱為線程&#xff08;thread&#xff09;。進程還擁有一個私有的虛擬地址空間&#xff0c;該空間…

基本SQL命令-您應該知道的數據庫查詢和語句列表

SQL stands for Structured Query Language. SQL commands are the instructions used to communicate with a database to perform tasks, functions, and queries with data.SQL代表結構化查詢語言。 SQL命令是用于與數據庫通信以執行任務&#xff0c;功能和數據查詢的指令。…

leetcode 5756. 兩個數組最小的異或值之和(狀態壓縮dp)

題目 給你兩個整數數組 nums1 和 nums2 &#xff0c;它們長度都為 n 。 兩個數組的 異或值之和 為 (nums1[0] XOR nums2[0]) (nums1[1] XOR nums2[1]) … (nums1[n - 1] XOR nums2[n - 1]) &#xff08;下標從 0 開始&#xff09;。 比方說&#xff0c;[1,2,3] 和 [3,2,1…

客戶細分模型_Avarto金融解決方案的客戶細分和監督學習模型

客戶細分模型Lets assume that you are a CEO of a company which have some X amount of customers in a city with 1000 *X population. Analyzing the trends/features of your customer and segmenting the population of the city to land new potential customers would …

用 Go 編寫一個簡單的 WebSocket 推送服務

用 Go 編寫一個簡單的 WebSocket 推送服務 本文中代碼可以在 github.com/alfred-zhon… 獲取。 背景 最近拿到需求要在網頁上展示報警信息。以往報警信息都是通過短信&#xff0c;微信和 App 推送給用戶的&#xff0c;現在要讓登錄用戶在網頁端也能實時接收到報警推送。 依稀記…

leetcode 231. 2 的冪

給你一個整數 n&#xff0c;請你判斷該整數是否是 2 的冪次方。如果是&#xff0c;返回 true &#xff1b;否則&#xff0c;返回 false 。 如果存在一個整數 x 使得 n 2x &#xff0c;則認為 n 是 2 的冪次方。 示例 1&#xff1a; 輸入&#xff1a;n 1 輸出&#xff1a;tr…

Java概述、環境變量、注釋、關鍵字、標識符、常量

Java語言的特點 有很多小特點&#xff0c;重點有兩個開源&#xff0c;跨平臺 Java語言是跨平臺的 Java語言的平臺 JavaSE JavaME--Android JavaEE DK,JRE,JVM的作用及關系(掌握) (1)作用 JVM&#xff1a;保證Java語言跨平臺 &#xff0…

寫游戲軟件要學什么_為什么要寫關于您所知道的(或所學到的)的內容

寫游戲軟件要學什么Im either comfortably retired or unemployed, I havent decided which. What I do know is that I am not yet ready for decades of hard-won knowledge to lie fallow. Still driven to learn new technologies and to develop new projects, I see the …

leetcode 342. 4的冪

給定一個整數&#xff0c;寫一個函數來判斷它是否是 4 的冪次方。如果是&#xff0c;返回 true &#xff1b;否則&#xff0c;返回 false 。 整數 n 是 4 的冪次方需滿足&#xff1a;存在整數 x 使得 n 4x 示例 1&#xff1a; 輸入&#xff1a;n 16 輸出&#xff1a;true …

梯度反傳_反事實政策梯度解釋

梯度反傳Among many of its challenges, multi-agent reinforcement learning has one obstacle that is overlooked: “credit assignment.” To explain this concept, let’s first take a look at an example…在許多挑戰中&#xff0c;多主體強化學習有一個被忽略的障礙&a…

三款功能強大代碼比較工具Beyond compare、DiffMerge、WinMerge

我們經常會遇到需要比較同一文件的不同版本&#xff0c;特別是代碼文件。如果人工去對比查看&#xff0c;勢必費時實力還會出現紕漏和錯誤&#xff0c;因此我們需要借助一些代碼比較的工具來自動完成這些工作。這里介紹3款比較流行且功能強大的工具。 1. Beyond compare這是一款…

shell腳本_Shell腳本

shell腳本In the command line, a shell script is an executable file that contains a set of instructions that the shell will execute. Its main purpose is to reduce a set of instructions (or commands) in just one file. Also it can handle some logic because it…

大數據與Hadoop

大數據的定義 大數據是指無法在一定時間內用常規軟件工具對其內容進行抓取、管理和處理的數據集合。 大數據的概念–4VXV 1,數據量大&#xff08;Volume&#xff09;2,類型繁多&#xff08;Variety &#xff09;3,速度快時效高&#xff08;Velocity&#xff09;4,價值密度低…

Arm匯編指令學習

ARM指令格式 ARM指令格式解析 opcode: 指令助記符,例如,MOV ,ADD,SUB等等 cond&#xff1a;指令條件碼表.下面附一張圖 {S}:是否影響CPSR的值. {.W .N}:指令寬度說明符,無論是ARM代碼還是Thumb&#xff08;armv6t2或更高版本&#xff09;代碼都可以在其中使用.W寬度說明符&…

facebook.com_如何降低電子商務的Facebook CPM

facebook.comWith the 2020 election looming, Facebook advertisers and e-commerce stores are going to continually see their ad costs go up as the date gets closer (if they haven’t already).隨著2020年選舉的臨近&#xff0c;隨著日期越來越近&#xff0c;Facebook…

Python中的If,Elif和Else語句

如果Elif Else聲明 (If Elif Else Statements) The if/elif/else structure is a common way to control the flow of a program, allowing you to execute specific blocks of code depending on the value of some data.if / elif / else結構是控制程序流程的常用方法&#x…

Hadoop安裝及配置

Hadoop的三種運行模式 單機模式&#xff08;Standalone,獨立或本地模式&#xff09;:安裝簡單,運行時只啟動單個進程,僅調試用途&#xff1b;偽分布模式&#xff08;Pseudo-Distributed&#xff09;:在單節點上同時啟動namenode、datanode、secondarynamenode、resourcemanage…

漏洞發布平臺-安百科技

一個不錯的漏洞發布平臺&#xff1a;https://vul.anbai.com/ 轉載于:https://blog.51cto.com/antivirusjo/2093758

Android 微信分享圖片

private String APP_ID "00000000000000000"; //微信 APPID private IWXAPI iwxapi; private void regToWx() {iwxapi WXAPIFactory.createWXAPI(context, APP_ID, true);//這里context記得初始化iwxapi.registerApp(APP_ID); } IMServer.getDiskBitmap(IMServer.u…

蒙蒂霍爾問題_常見的邏輯難題–騎士和刀,蒙蒂·霍爾和就餐哲學家的問題解釋...

蒙蒂霍爾問題While not strictly related to programming, logic puzzles are a good warm up to your next coding session. You may encounter a logic puzzle in your next technical interview as a way to judge your problem solving skills, so its worth being prepare…