使用Retrofit的一些实例

来源:互联网 发布:dsd音乐播放软件 编辑:程序博客网 时间:2024/06/07 03:11

刚开始熟悉Retrofit ,并正在将项目中的网络框架换为retrofit。

添加依赖:

    compile 'com.squareup.retrofit2:retrofit:2.1.0'//Retrofit2所需要的包    compile 'com.squareup.retrofit2:converter-gson:2.1.0'//ConverterFactory的Gson依赖包

Retrofit的网络接口服务的包装类

public class RetrofitWrapper {    private static RetrofitWrapper retrofitWrapper;    private Retrofit retrofit;    private RetrofitWrapper() {        retrofit = new Retrofit.Builder().baseUrl(AppConfig.RETROFIT_URL)                .addConverterFactory(GsonConverterFactory.create())                .build();    }    /**     * 单列模式     */    public static RetrofitWrapper getWrapperInstance() {        if (retrofitWrapper == null) {            synchronized (RetrofitWrapper.class) {                if (retrofitWrapper == null) {                    retrofitWrapper = new RetrofitWrapper();                }            }        }        return retrofitWrapper;    }    public <T> T create(final Class<T> service) {        return retrofit.create(service);    }}

定义接口:

public interface RetrofitApi {    /**     * 登录     */    @POST("servRoot")    Call<LoginBean> doLoginResult(@QueryMap Map<String, String> map);    }

通过 baseUrl(AppConfig.RETROFIT_URL)+@POST(“servRoot”)
拼接成完整的请求URL:”http://www.xxxx.cn/servRoot”

发起请求的入口:

public class RetrofitModel {    private RetrofitApi retrofitApi;    private static RetrofitModel retrofitModel;    /**     * 单列模式     */    public static RetrofitModel getModelInstance() {        if (retrofitModel == null) {            retrofitModel = new RetrofitModel();        }        return retrofitModel;    }    private RetrofitModel(){        retrofitApi = RetrofitWrapper.getWrapperInstance().create(RetrofitApi.class);    }    /**     * 登录     */    public Call<LoginBean> login(Map<String,String> map) {        Call<LoginBean> loginCall = retrofitApi.doLoginResult(map);        return loginCall;    } }

发起登录的请求:

    private RetrofitModel retrofitModel;    retrofitModel = RetrofitModel.getModelInstance();    /**     * 使用retrofit登录     */    public void retrofitLogin() {        Map<String, String> map = new HashMap<>();        map.put("user_name", username);        map.put("user_pwd", userpass);        map.put("className", "com.ycya.service.UserInfoService");        map.put("methodName", "login");        //这里的泛型我已经知道了返回数据的结构         //如果不知道的话  可以将泛型定义为:Call<ResponseBody>           // 然后在请求成功后ResponseBody.body().string()  查看结构 来解析        Call<LoginBean> call = retrofitModel.login(map);        call.enqueue(new Callback<LoginBean>() {            @Override            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {                if (response.isSuccessful()) {                    //得到返回的泛型数据                    LoginBean loginBean = response.body();                }            }            @Override            public void onFailure(Call<LoginBean> call, Throwable t) {            }        });    }

上传单张图片
参考了很多网上的方法 都传不上去 后台报空 后面找到了官方文档 拷贝实例代码 直接Ok
定义接口:

RetrofitApi中:

    /**     * 事故上传现场图片     *      * id  pathFile  这两个后台需要的     * 最后那个需要传的图片     */    @Multipart    @POST("imgupload")    Call<ResponseBody> uploadImg(@Part("id") RequestBody id,                                 @Part("pathFile") RequestBody pathFile,                                 @Part MultipartBody.Part img);

RetrofitModel中:

    /**     * 事故上传中的现场图片     */    public Call<ResponseBody> uploadImg(RequestBody id, RequestBody pathFile, MultipartBody.Part img){        Call<ResponseBody> call=retrofitApi.uploadImg(id,pathFile,img);        return call;    }

上传:

    /**     * 上传现场图片     */    public void uploadImg1(String path) {        //id        RequestBody id =RequestBody.create(MediaType.parse("multipart/form-data"), "0");        //pathFile        RequestBody pathFile =RequestBody.create(MediaType.parse("multipart/form-data"), "filestore/uploadimg");        //1、根据地址拿到File        File file = new File(path);        //2、创建RequestBody,其中`multipart/form-data`为编码类型        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);        //3、创建`MultipartBody.Part`,其中需要注意第一个参数`filename`需要与服务器对应,也就是`键`        MultipartBody.Part  part = MultipartBody.Part.createFormData("filename", file.getName(), requestFile);        Call<ResponseBody> call = retrofitModel.uploadImg(id,pathFile, part);        call.enqueue(new Callback<ResponseBody>(){            @Override            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {                if (response.isSuccessful()){                    try {                        KLog.e(response.body().string());                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }            @Override            public void onFailure(Call<ResponseBody> call, Throwable t) {                KLog.e("onFailure");            }        });    }

还有其他的方法方式没试过,后面如果试了,ok的 会更上来。

某个文档 (例子挺多):https://futurestud.io/tutorials/retrofit-2-basics-of-api-description

参考:http://blog.csdn.net/u011974987/article/details/50895633

0 0
原创粉丝点击