Retrofit基础Http请求

    |     2016年9月2日   |   Android经验   |     0 条评论   |    2846

简介

Retrofit是Square开 发的一个Android和Java的REST客户端库。这个库非常简单并且具有很多特性,相比其他的网络库,更容易让初学者快速掌握。它可以处理GET、 POST、PUT、DELETE…等请求

概述

retrofit_bs
1) POJO或模型实体类 : 从服务器获取的JSON数据将被填充到这种类的实例中。

public class StudentBean {
    private String name;
    private int age;
}

2) 接口 : 我们需要创建一个接口来管理像GET,POST…等请求的URL,这是一个服务类。

public interface RetrofitCall {
    @GET("/student")
    Call<StudentBean> getStudent();
}

3) RestAdapter类 : 这是一个REST客户端(RestClient)类,retrofit中默认用的是Gson来解析JSON数据,你也可以设置自己的JSON解析器,比如jackson。
一般采用下术方法调用:

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

            RetrofitCall call = retrofit.create(RetrofitCall.class);
            Call<StudentBean> mCall = call.getStudent();
            mCall.enqueue(new Callback<StudentBean>() {
                @Override
                public void onResponse(Call<StudentBean> call, Response<StudentBean> response) {

                }

                @Override
                public void onFailure(Call<StudentBean> call, Throwable t) {

                }
        });

添加Retrofit库到项目中

Gradle :

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

目前,2.1.0是最新的版本. 你可以在这里获取更新的版本。

基本的HTTP请求

在Retrofit中使用注解的方式来区分请求类型.比如@GET("")表示一个GET请求,括号中的内容为请求的地址.
格式	含义
@GET	 表示这是一个GET请求
@POST	 表示这个一个POST请求
@PUT	 表示这是一个PUT请求
@DELETE	 表示这是一个DELETE请求
@HEAD	 表示这是一个HEAD请求
@OPTIONS 表示这是一个OPTION请求
@PATCH	 表示这是一个PAT请求

Retrofit可实现基本HTTP请求,包括GET,POST,PUT,DELETE等.
1.GET请求

GET("/record")
Call<PhoneResult> getResult();
2.POST请求

@POST("/record")
Call<PhoneResult> getResult();
3.PUT请求

@PUT("/record")
Call<PhoneResult> getResult();
4.DELETE请求

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

服务器接口类型

服务器接口有很多中,本人经验有限,目前接触较多为以下几种:

直接请求型

即直接对某一地址或组合某一地址发起请求

如:对/result和/result/{id}发起GET请求,其中{id}中的id在实际使用时填写实际值即可.

带参查询型

对某一地址进行带参查询请求

如:https://www.baidu.com/s?wd=123为对接口https://www.baidu.com/s进行参数为wd=123的GET查询请求.

带Header型

 即请求时要求带上Header

Retrofit中如何写?

直接请求型

1.如果是直接请求某一地址,写法如下:

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

2.如果是组合后直接请求,如/result/{id}写法如下:

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,代码如下:
比如要更新某个账户信息,其接口地址为/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
参考:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0418/2748.html

转载请注明来源:Retrofit基础Http请求

上一篇:

下一篇:

回复 取消