📜  安卓Retofit 2 介绍|设置 1

📅  最后修改于: 2021-10-19 08:19:13             🧑  作者: Mango

我把它分成了 3 个部分。我假设读者具有 Android 和Java 的基本知识。

介绍

Retrofit 2 是由 square 为 Android 和Java构建的类型安全 REST 客户端,旨在简化 RESTful Web 服务的使用。 Retrofit 2 使用 OkHttp 作为系统管理层并以它为基础。 Retrofit 自然地使用 POJO (PlainOldJavaObject) 序列化 JSON 反应,该 POJO 必须具有 JSON Structure 的前沿特征。要序列化 JSON,我们需要一个转换器先将其转换为 Gson。 Retrofit 比其他库简单得多,我们不必解析我们的 json,它直接返回对象,但有一个缺点,它不支持从服务器加载图像,但我们可以使用 picasso。现在我们应该进行一些实际的实现,这将使您更好地理解。

执行

步骤 1:为了在我们的 android 项目中使用 Retrofit,首先我们必须在 gradle 文件中添加依赖项。要添加依赖项,请在您的 Android 项目中打开 app/build.gradle 文件并在其中添加以下几行。在依赖项中添加这些行{}

compile'com.google.code.gson:gson:2.6.2'
compile'com.squareup.retrofit2:retrofit:2.0.2'
compile'com.squareup.retrofit2:converter-gson:2.0.2'

第 2 步:我们现在应该在 Manifestfile 中添加 InternetPermission。打开 manifest.xml 文件并添加以下行。

users-permission android:name="android.permission.INTERNET"

第 3 步:为了使用改造 2 从服务器检索数据,我们需要一个模型类。我们将制作模型类以从服务器检索数据。为了制作模型类,我们应该知道 json 的外观。
假设我们的 json 看起来像这样:

"current_page":1,
"data":
[
{
"id":1,
"source":"http:\/\/mhrd.gov.in\/sites\/upload_files\/mhrd\/files\/upload_document\/NSISGE-Scheme-Copy.pdf",
"name":"National Scheme of Incentive to Girls for Secondary Education (NSIGSE)",
"sector":"Education",
"government":"Central",
"eligible_beneficiaries":"Individual",
"requirements":"i. Girls, who pass class VIII examination and enroll for class IX in State\/UT Government, Government-aided or local body schools.\nii. Girls should be below 16 years of age (as on 31st March) on joining class IX\niii. Girls studying in private un-aided schools and enrolled in schools run by Central Government like KVS, NVS and CBS affiliated Schools are excluded.",
"benefits":"FD of Rs.3000 in the name of selected girls. The girls are entitled to withdraw the sum along with interest thereon on reaching 18 years of age and on passing 10th class examination.",
"how_to_apply":"Contact Principal\/Headmaster of the School",
"profession":"",
"nationality":"",
"gender":"Female",
"social_category":[
"SC",
"ST",
"Girls from Kasturba Gandhi Balika Vidyalayas"
],
"bpl":"",
"maximum_income":"",
"maximum_monthly_income":"",
"min_age":14,
"max_age":18,
"age_relaxation":"",
"qualification":8,
"employed":"",
"domicile":"",
"marital_status":"Unmarried",
"parents_profession":"",
"person_with_disabilities":"",
"current_student":"Yes",
"min_marks_in_previous_examination":"",
"religion":"",
"isDeleted":"false",
"isLatest":"false",
"isPopular":"false",
"isHtml":"false",
"state_url":"http:\/\/161.202.178.14\/kalyani\/storage\/states\/AORGzbxjrB3zHhAyfs6zTqpt3pQhJsHRwSC4JVBs.png",
"sector_url":"http:\/\/161.202.178.14\/kalyani\/storage\/sector\/lDASDAsje3BuWQYgaBCqKKWwkfKEuqIvVYp3dp53.png"
},
....
]"from":1,
"last_page":75,
"next_page_url":"http:\/\/localhost:8081\/\/api\/v1\/search?page=2",
"per_page":10,
"prev_page_url":null,
"to":10,
"total":741

如果您看到 json,您会发现 json 包含不同的字段,例如 source、stateurl、sectorurl、id、name、sector、government、id、name、sector、government、qualifiedBeneficiarieand 等我们创建的所有字段的 getter setter 并使用了 Parcelable (https://developer.android.com/reference/android/os/Parcelable.html)。

这是模型类的代码,请阅读它以更好地理解。

import android.os.Parcel;
import android.os.Parcelable;
  
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
  
public class Scheme implements Parcelable {
  
    public static final Creator CREATOR = new Creator ( ) {
        @Override
        public Scheme createFromParcel ( Parcel source ) {
            return new Scheme ( source );
        }
  
        @Override
        public Scheme[] newArray ( int size ) {
            return new Scheme[size];
        }
    };
    @SerializedName("source")
    @Expose
    private String source;
    @SerializedName("state_url")
    @Expose
    private String stateurl;
    @SerializedName("sector_url")
    @Expose
    private String sectorurl;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("sector")
    @Expose
    private String sector;
    @SerializedName("government")
    @Expose
    private String government;
    @SerializedName("eligible_beneficiaries")
    @Expose
    private String eligibleBeneficiaries;
    @SerializedName("maximum_income")
    @Expose
    private String income;
    @SerializedName("social_category")
    @Expose
    private String[] socialCategory;
    @SerializedName("religion")
    @Expose
    private String religion;
    @SerializedName("requirements")
    @Expose
    private String requirements;
    @SerializedName("benefits")
    @Expose
    private String benefits;
    @SerializedName("how_to_apply")
    @Expose
    private String howToApply;
    @SerializedName("gender")
    @Expose
    private String gender;
    @SerializedName("min_age")
    @Expose
    private Integer minAge;
    @SerializedName("max_age")
    @Expose
    private Integer maxAge;
    @SerializedName("qualification")
    @Expose
    private String qualification;
    @SerializedName("marital_status")
    @Expose
    private String maritalStatus;
    @SerializedName("bpl")
    @Expose
    private String bpl;
    @SerializedName("disability")
    @Expose
    private String disability;
  
    public Scheme ( ) {
    }
  
    protected Scheme ( Parcel in ) {
        this.source = in.readString ( );
        this.stateurl = in.readString ( );
        this.sectorurl = in.readString ( );
        this.id = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.name = in.readString ( );
        this.sector = in.readString ( );
        this.government = in.readString ( );
        this.eligibleBeneficiaries = in.readString ( );
        this.income = in.readString ( );
        this.socialCategory = in.createStringArray ( );
        this.religion = in.readString ( );
        this.requirements = in.readString ( );
        this.benefits = in.readString ( );
        this.howToApply = in.readString ( );
        this.gender = in.readString ( );
        this.minAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.maxAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.qualification = in.readString ( );
        this.maritalStatus = in.readString ( );
        this.bpl = in.readString ( );
        this.disability = in.readString ( );
    }
  
    public String getBpl ( ) {
        return bpl;
    }
  
    public void setBpl ( String bpl ) {
        this.bpl = bpl;
    }
  
    public String getDisability ( ) {
        return disability;
    }
  
    public void setDisability ( String disability ) {
        this.disability = disability;
    }
  
    public String getStateurl ( ) {
        return stateurl;
    }
  
    public void setStateurl ( String stateurl ) {
        this.stateurl = stateurl;
    }
  
    public String getSectorurl ( ) {
        return sectorurl;
    }
  
    public void setSectorurl ( String sectorurl ) {
        this.sectorurl = sectorurl;
    }
  
    public String getIncome ( ) {
        return income;
    }
  
    public void setIncome ( String income ) {
        this.income = income;
    }
  
    public String[] getSocialCategory ( ) {
        return socialCategory;
    }
  
    public void setSocialCategory ( String[] socialCategory ) {
        this.socialCategory = socialCategory;
    }
  
    public String getReligion ( ) {
        return religion;
    }
  
    public void setReligion ( String religion ) {
        this.religion = religion;
    }
  
    public String getRequirements ( ) {
        return requirements;
    }
  
    public void setRequirements ( String requirements ) {
        this.requirements = requirements;
    }
  
    public String getSource ( ) {
        return source;
    }
  
    public void setSource ( String source ) {
        this.source = source;
    }
  
    public Integer getId ( ) {
        return id;
    }
  
    public void setId ( Integer id ) {
        this.id = id;
    }
  
    public String getName ( ) {
        return name;
    }
  
    public void setName ( String name ) {
        this.name = name;
    }
  
    public String getSector ( ) {
        return sector;
    }
  
    public void setSector ( String sector ) {
        this.sector = sector;
    }
  
    public String getGovernment ( ) {
        return government;
    }
  
    public void setGovernment ( String government ) {
        this.government = government;
    }
  
    public String getEligibleBeneficiaries ( ) {
        return eligibleBeneficiaries;
    }
  
    public void setEligibleBeneficiaries ( String eligibleBeneficiaries ) {
        this.eligibleBeneficiaries = eligibleBeneficiaries;
    }
  
    public String getBenefits ( ) {
        return benefits;
    }
  
    public void setBenefits ( String benefits ) {
        this.benefits = benefits;
    }
  
    public String getHowToApply ( ) {
        return howToApply;
    }
  
    public void setHowToApply ( String howToApply ) {
        this.howToApply = howToApply;
    }
  
    public String getGender ( ) {
        return gender;
    }
  
    public void setGender ( String gender ) {
        this.gender = gender;
    }
  
    public Integer getMinAge ( ) {
        return minAge;
    }
  
    public void setMinAge ( Integer minAge ) {
        this.minAge = minAge;
    }
  
    public Integer getMaxAge ( ) {
        return maxAge;
    }
  
    public void setMaxAge ( Integer maxAge ) {
        this.maxAge = maxAge;
    }
  
    public String getQualification ( ) {
        return qualification;
    }
  
    public void setQualification ( String qualification ) {
        this.qualification = qualification;
    }
  
    public String getMaritalStatus ( ) {
        return maritalStatus;
    }
  
    public void setMaritalStatus ( String maritalStatus ) {
        this.maritalStatus = maritalStatus;
    }
  
    public String getSocialCategoryString(){
        if(socialCategory != null && socialCategory.length > 0){
            return android.text.TextUtils.join(",", socialCategory);
        }
        return null;
    }
  
    @Override
    public int describeContents ( ) {
        return 0;
    }
  
    @Override
    public void writeToParcel ( Parcel dest, int flags ) {
        dest.writeString ( this.source );
        dest.writeString ( this.stateurl );
        dest.writeString ( this.sectorurl );
        dest.writeValue ( this.id );
        dest.writeString ( this.name );
        dest.writeString ( this.sector );
        dest.writeString ( this.government );
        dest.writeString ( this.eligibleBeneficiaries );
        dest.writeString ( this.income );
        dest.writeStringArray ( this.socialCategory );
        dest.writeString ( this.religion );
        dest.writeString ( this.requirements );
        dest.writeString ( this.benefits );
        dest.writeString ( this.howToApply );
        dest.writeString ( this.gender );
        dest.writeValue ( this.minAge );
        dest.writeValue ( this.maxAge );
        dest.writeString ( this.qualification );
        dest.writeString ( this.maritalStatus );
        dest.writeString ( this.bpl );
        dest.writeString ( this.disability );
    }
}

您一定已经注意到我们在 json 中使用了分页(我们以 10 个为一组检索数据)。为了处理这个分页,我们将再创建一个Java文件。

这是分页代码,请阅读以更好地理解。

import android.os.Parcel;
import android.os.Parcelable;
  
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
  
import java.util.ArrayList;
  
  
public class Page implements Parcelable {
  
    public static final Creator CREATOR = new Creator ( ) {
        @Override
        public Page createFromParcel ( Parcel source ) {
            return new Page ( source );
        }
  
        @Override
        public Page[] newArray ( int size ) {
            return new Page[size];
        }
    };
    @SerializedName("current_page")
    @Expose
    private Integer currentPage;
    @SerializedName("data")
    @Expose
    private ArrayList data = null;
    @SerializedName("from")
    @Expose
    private Integer from;
    @SerializedName("last_page")
    @Expose
    private Integer lastPage;
    @SerializedName("next_page_url")
    @Expose
    private String nextPageUrl;
    @SerializedName("path")
    @Expose
    private String path;
    @SerializedName("per_page")
    @Expose
    private Integer perPage;
    @SerializedName("prev_page_url")
    @Expose
    private String prevPageUrl;
    @SerializedName("to")
    @Expose
    private Integer to;
    @SerializedName("total")
    @Expose
    private Integer total;
  
    public Page ( ) {
    }
  
    protected Page ( Parcel in ) {
        this.currentPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.data = in.createTypedArrayList ( Scheme.CREATOR );
        this.from = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.lastPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.nextPageUrl = in.readString ( );
        this.path = in.readString ( );
        this.perPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.prevPageUrl = in.readString ( );
        this.to = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
        this.total = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
    }
  
    public Integer getCurrentPage() {
        return currentPage;
    }
  
    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }
  
    public ArrayList getData ( ) {
        return data;
    }
  
    public void setData ( ArrayList data ) {
        this.data = data;
    }
  
    public Integer getFrom() {
        return from;
    }
  
    public void setFrom(Integer from) {
        this.from = from;
    }
  
    public Integer getLastPage() {
        return lastPage;
    }
  
    public void setLastPage(Integer lastPage) {
        this.lastPage = lastPage;
    }
  
    public String getNextPageUrl() {
        return nextPageUrl;
    }
  
    public void setNextPageUrl(String nextPageUrl) {
        this.nextPageUrl = nextPageUrl;
    }
  
    public String getPath() {
        return path;
    }
  
    public void setPath(String path) {
        this.path = path;
    }
  
    public Integer getPerPage() {
        return perPage;
    }
  
    public void setPerPage(Integer perPage) {
        this.perPage = perPage;
    }
  
    public String getPrevPageUrl ( ) {
        return prevPageUrl;
    }
  
    public void setPrevPageUrl ( String prevPageUrl ) {
        this.prevPageUrl = prevPageUrl;
    }
  
    public Integer getTo() {
        return to;
    }
  
    public void setTo(Integer to) {
        this.to = to;
    }
  
    public Integer getTotal() {
        return total;
    }
  
    public void setTotal(Integer total) {
        this.total = total;
    }
  
    @Override
    public int describeContents ( ) {
        return 0;
    }
  
    @Override
    public void writeToParcel ( Parcel dest, int flags ) {
        dest.writeValue ( this.currentPage );
        dest.writeTypedList ( this.data );
        dest.writeValue ( this.from );
        dest.writeValue ( this.lastPage );
        dest.writeString ( this.nextPageUrl );
        dest.writeString ( this.path );
        dest.writeValue ( this.perPage );
        dest.writeString ( this.prevPageUrl );
        dest.writeValue ( this.to );
        dest.writeValue ( this.total );
    }
}

现在我们已经创建了模型类(用于处理数据)和分页类(在 json 中处理分页)。现在我们必须创建适配器和 API 服务提供者并显示我们的数据。我们将在本教程的第二和第三部分中介绍这些内容。

参考 :
http://square.github.io/retrofit/