[原創]Retrofit使用教程(二)

上一篇文章講述了Retrofit的簡單使用,此次咱們學習一下Retrofit的各類HTTP請求.java

Retrofit基礎

在Retrofit中使用註解的方式來區分請求類型.好比@GET("")表示一個GET請求,括號中的內容爲請求的地址.git

格式 含義
@GET 表示這是一個GET請求
@POST 表示這個一個POST請求
@PUT 表示這是一個PUT請求
@DELETE 表示這是一個DELETE請求
@HEAD 表示這是一個HEAD請求
@OPTIONS 表示這是一個OPTION請求
@PATCH 表示這是一個PAT請求

基本的HTTP請求

Retrofit可實現基本HTTP請求,包括GET,POST,PUT,DELETE等.github

1.GET請求json

@GET("/record")
Call<PhoneResult> getResult();

2.POST請求api

@POST("/record")
Call<PhoneResult> getResult();

3.PUT請求服務器

@PUT("/record")
Call<PhoneResult> getResult();

4.DELETE請求微信

@DELETE("/record")
Call<PhoneResult> getResult();

服務器接口類型

服務器接口有不少中,本人經驗有限,目前接觸較多爲如下幾種:post

直接請求型

即直接對某一地址或組合某一地址發起請求學習

如:對/result/result/{id}發起GET請求,其中{id}中的id在實際使用時填寫實際值便可.ui

帶參查詢型

對某一地址進行帶參查詢請求

如:https://www.baidu.com/s?wd=123爲對接口https://www.baidu.com/s進行參數爲wd=123GET查詢請求.

帶Header型

 即請求時要求帶上Header

Retrofit中如何寫?

直接請求型

1.若是是直接請求某一地址,寫法以下:

@GET("/record")
Call<PhoneResult> getResult();

2.若是是組合後直接請求,如/result/{id}寫法以下:

@GET("/result/{id}")
Call<PhoneResult> getResult(@Path("id") String id);

帶參查詢型

如12306的查詢接口https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-03-18&from_station=BJP&to_station=CDW,寫法以下:

@GET("/otn/lcxxcx/query")
Call<Result> query(@Query("purpose_codes") String codes, @Query("queryDate") String date,
    @Query("from_station") String from, @Query("to_station") String to)

帶Header型

好比要更新某個帳戶信息,其接口地址爲/info,須要帶的Header有設備信息device,系統版本version,還要帶請求參數要更新帳戶的id,代碼以下:

@POST("/info")
Call<Object> updateInfo(@Header("device") String device, @Header("version") int version,
                        @Field("id") String id);

注:本想給每一種請求添加一個請求實例,可是確實不太好找.

實例

找了好久發現多說提供了一些POST請求接口,下面就以多說的接口爲例,看一下如何使用Retrofit寫請求.

基礎URL

多說的接口基礎地址爲:http://api.duoshuo.com,則構建Retrofit實例代碼以下:

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("http://api.duoshuo.com")
        .build();

獲取文章評論、轉發數

接口地址爲:/threads/counts

HTTP請求方式:GET

請求示例爲:http://api.duoshuo.com/threads/counts.json?short_name=official&threads=4ff1cbc43ae636b72a00001d

後面的.json爲返回數據的格式,此處咱們使用json格式.

請求代碼以下:

@GET("/threads/counts.json")
Call<Object> getCommit(@Query("short_name") String shortName,
                       @Query("threads") String threads);

匿名發表新評論

接口地址爲:/posts/create

HTTP請求方式:POST

請求示例爲:

Request URL:http://api.duoshuo.com/posts/create.json
Request Method:POST
Post Data:short_name=official&author_email=jp.chenyang%40gmail.com&author_name=Perchouli&thread_id=1152923703638301959&author_url=http%3A%2F%2Fduoshuo.com&message=匿名發表新評論

1.Field方式實現

@FormUrlEncoded
    @POST("/posts/create.json")
    Call<CommitResult> createCommit(@Field("secret") String secret,
                                    @Field("short_name") String shortName,
                                    @Field("author_email") String authorEmail,
                                    @Field("author_name") String authorName,
                                    @Field("thread_key") String threadKey,
                                    @Field("author_url") String author_url,
                                    @Field("message") String message);

2.Field Map實現方式

@FormUrlEncoded
    @POST("/posts/create.json")
    Call<CommitResult> createCommit(@FieldMap Map<String, String> map);

獲取Map方式以下:

public class CommitParam {

    private String short_name;
    private String author_email;
    private String author_name;
    private String thread_id;
    private String author_url;
    private String message;

    public String getShort_name() {
        return short_name;
    }

    public void setShort_name(String short_name) {
        this.short_name = short_name;
    }

    public String getAuthor_email() {
        return author_email;
    }

    public void setAuthor_email(String author_email) {
        this.author_email = author_email;
    }

    public String getAuthor_name() {
        return author_name;
    }

    public void setAuthor_name(String author_name) {
        this.author_name = author_name;
    }

    public String getThread_id() {
        return thread_id;
    }

    public void setThread_id(String thread_id) {
        this.thread_id = thread_id;
    }

    public String getAuthor_url() {
        return author_url;
    }

    public void setAuthor_url(String author_url) {
        this.author_url = author_url;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, String> createCommitParams(){
        Map<String, String> params = new HashMap<>();
        params.put("short_name", short_name);
        params.put("author_email", author_email);
        params.put("author_name", author_name);
        params.put("thread_id", thread_id);
        params.put("author_url", author_url);
        params.put("message", message);
        return params;
    }
}

項目地址在此:Dev-Wiki/RetrofitDemo

更多文章請移步個人博客:DevWiki Blog

重要說明

想隨時獲取最新博客文章更新,請關注公共帳號DevWiki,或掃描下面的二維碼:

微信公共號

相關文章
相關標籤/搜索