Android 使用Retrofit2.0 + OKHttp 实现 HTTP协议请求

来源:互联网 发布:淘宝客服的岗位要求 编辑:程序博客网 时间:2024/06/06 00:40

记得之前要想实现http协议自己封装会比较繁琐,后来有了OKHttp,另http请求更加轻便。

今天主要来说下Retrofit2.0的用法,由于本人之前几年用的as3 air,也是最近才开始重新回来写Android,对于Retrofit的使用经验为0,上手就是看的2.0,个人觉得Retrofit2.0用起来相比OKHttp更加方便代码也很容易理解,但是网上关于Retrofit2.0的资料很少,于是决定来记录一下,也方便大家参考下。


个人理解,Retrofit分为三大块:

1、InterfaceService:发送请求的Service接口。

2、Request:发送的Request请求参数。

3、Response:返回的相应。


由于大多人用的数据发送请求格式比较多的是JSON字符串格式,所以先来讲讲Json字符串请求,json字符串返回的格式,解析json字符串这里我用的是Gson。


这里先简单的实现一个获取短信验证码的请求:


首先先导入所需要的工具:

compile 'com.squareup.okhttp:okhttp:2.6.0'    compile 'com.google.code.gson:gson:2.5'    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'



一般开发一个应用,需要多次调用请求,如果我们每调用一次都实例化一个Retrofit会很繁琐,那么大家应该都知道,要封装一个实例吧。大家都知道,请求时每次会有很多固定的参数,比如APPId,sign签证等等,每次都写一遍很繁琐,于是,我们就把这些参数在请求头里定义,这样就只需要实例定义一遍,后面只需要传请求需要的参数就可以了,代码也方便很多(当然,https请求就另当别论了,目前国内主流还是http请求)

public static Retrofit getInstance() {        if (instaince == null) {            OkHttpClient client = new OkHttpClient();            client.interceptors().add(new Interceptor() {                @Override                public Response intercept(Chain chain) throws IOException {                    Request original = chain.request();                    String str1 = "验证参数1";                    String str2 = "验证参数2";                                   /**                     * 用header存储固定参数,主要验证用                     */                    // Customize the request                    Request request = original.newBuilder()                            .addHeader("appId", str1)                            .addHeader("sign", str2)                            .method(original.method(), original.body())                            .build();                    Response response = chain.proceed(request);                    return response;                }            });            <pre name="code" class="html"><span style="white-space:pre"></span>instaince <span style="font-family: Arial, Helvetica, sans-serif;">= new Retrofit.Builder()</span>
.baseUrl(Constants.APP_HOST) //请求url .client(client) //自定义OkHttpClient,即每次发送请求时都会调用一次这个方法,然后把固定参数加在请求中发送
.addConverterFactory(GsonConverterFactory.create()) //定义Gson解析 .build(); } return instaince; }

然后,定义一个http请求返回转换后的Response类

public class BaseResponse {    protected int result;    protected String msg;    public int getResult() {        return result;    }    public void setResult(int result) {        this.result = result;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}

定义一个请求Request类,用于封装请求时需要的参数:

public class GetVerifyRequest {    private String mobile;    public GetVerifyRequest(String mobile){        this.mobile = mobile;    }    public String getMobile() {        return mobile;    }    public void setMobile(String mobile) {        this.mobile = mobile;    }}
mobile就是需要传过去的参数;


接着,我们该实现一个请求接口了:

public interface VerifyCodeService {    @POST("tools/getVerifyCode")    Call<BaseResponse> getVerifyCode(@Body GetVerifyRequest map);}
简单几行代码就结束了,是不是很方便,这个接口可以定义请求类型,比如固定头@Header 、请求方式POST/GET 、请求类型@Mutipart(Mutipart/form-data)@FormUrlEncoded表单格式等等

@Body就是过去的请求参数


最后,我们需要实现发送请求了

VerifyCodeService verifyCodeService = retrofit.create(VerifyCodeService.class);  //获取接口类实例                retrofit.Call<BaseResponse> repos = verifyCodeService.getVerifyCode(                        new GetVerifyRequest(“12345678”)));                repos.enqueue(new Callback<BaseResponse>() {<span style="white-space:pre"></span>//发送异步请求                    @Override                    public void onResponse(retrofit.Response<BaseResponse> response, Retrofit retrofit) {                        BaseResponse result = response.body();                    }                    @Override                    public void onFailure(Throwable t) {                        System.out.println(t.toString());                    }                });

好了!简单的一个Rtrofit请求流程结束了,在返回得到的result中就有信息了。相当方便,之后要实现其他的接口,只需要再实现一个Service,一个Request以及Response就可以啦!


总结:

整个流程就是这样,不需要去关心转换,只需要传入相关的mobile值,就会返回结果,完全的面向对象模式。

以上流程内部将Request类转成了{mobile="12345678"}json字符串发送,返回{result=0,msg="发送成功"},然后自动返回一个gson转换后的类,BaseResponse中的result = 0,msg = “发送成功”;


-------------分割线----------------

另外一个比较用的就是上传图片文件:

一般上传图片我们都是以multipart/form-data方式上传,这样Service接口就得这样实现了:

public interface InfoService {    @Multipart    @POST("uif/completeAddress")    Call<BaseResponse> completeAddress(@Part("userId") RequestBody userId            , @Part("image\"; filename=\"image.png ")RequestBody image);}

首先定义@Mutipart,参数都得通过@Part传入,userId是String字符串,image为File文件,这里需要注意,官方文档说明String可以直接传入String值,但是会出现双层双引号的问题,那就得传入RequestBody;文件首先先定义json的key值:image,接着要定义filename=""即可

retrofit.Call<BaseResponse> respo = service.completeAddress(               toRequestBody(UserUtil.getInstance().getUserId())                , toRequestBody(new File(mFilePath)));
public static RequestBody toRequestBody(String value) {        return RequestBody.create(MediaType.parse("text/plain"), value);    }    public static RequestBody toRequestBody(File value) {        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), value);        return body;    }

好了,一张图片就成功上传到服务器了,这里写法还是有点绕,期待后面版本更新;

整理的可能稍微有点乱,希望大家能明白;


参考资料:

https://futurestud.io/blog/retrofit-2-upgrade-guide-from-1-9

http://blog.csdn.net/biezhihua/article/details/49232289








2 0
原创粉丝点击