Retrofit网络请求框架的基本使用

Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的.来看看它的基本使用方法:

1.定义一个自定义的接口,这里需要稍作说明,@GET注解就表示get请求,@Query表示请求参数,将会以key=value的方式拼接在url后面;

其中的方法都是自定义的;

public interface NetInterFace {
    //retrofit 原生的请求
    @GET("/article/list/text?page=1")
    Call<ResponseBody> getNetData();

    // 自动解析的请求
    @GET("/article/list/text?page=1")
    Call<Modle> getNetDataWithModle();
    @GET("/article/list/text?")
    Call<Modle> getNetDataWithPage(@Query("page") String page);

    /**
     * 传递多个参数  注意要加一个参数的泛型
     * @return
     */
    @GET("/article/list/text?")
    Call<Modle> getNetDataWithParams(@QueryMap Map<String ,String> map);

    /**
     * 动态替换路径
     */
   @GET("/article/list/{path}?page=1")
    Call<ResponseBody> getNetDataWithPath(@Path("path") String path);

    /**
     * 动态替换路径和参数
     */
    @GET("/article/list/{lala}?")
    Call<ResponseBody> getNetDataWithPathParams(@Path("lala")String path,@QueryMap Map<String ,String> params);

    /**
     * 完全和基地址无关 ,会按照你穿过来的地址去发送网络请求
     * @param url
     * @return
     */
    @GET
    Call<ResponseBody> getNetDataWithUrl(@Url String url);

    /**
     *  retrofit 发送post请求 动态传值
     * @param url
     * @param username
     * @param password
     * @return
     */
    @POST
    @FormUrlEncoded
    Call<ResponseBody> postNetDataWithParam(@Url String url,@Field("username")String username,@Field("pwd")String password);

    @POST("{test}")
    @FormUrlEncoded
    Call<ResponseBody> postNetDataWithPathParmas(@Path("test") String path, @FieldMap Map<String ,String> map);

}
2. 需要创建一个Retrofit的实例,并完成相应的配置;

addConverterFactory方法表示需要用什么转换器来解析返回值,GsonConverterFactory.create()表示调用Gson库来解析json返回值,具体的下文还会做详细介绍。

 //设置基地址 基地址 必须以"/" 结尾 ,经测试 得:外网是可以不加,内网需要加 ,如果 都加上,就不会有错
        mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.BASE_URL)
                // 添加转换工厂(用于传话 String 和实现类的 ,自动帮你解析json)
                .addConverterFactory(GsonConverterFactory.create()).build();
3.生成Call对象;通过自定义的接口的方法来生成. Call在Retrofit中就是行使网络请求并处理返回值的类,调用的时候会把需要拼接的参数传递进去,:

 mNetInterface = mRetrofit.create(NetInterFace.class);
        Call<ResponseBody> bodyCall = mNetInterface.getNetData();
4.完成网络请求:同步或者异步请求:

如果是同步请求则该请求会在本线程中执行;

 try {
            bodyCall.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
或者异步请求:

 bodyCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                   if (response.isSuccessful()){
                       try {
                           // 获取body里面的内容
                           String string = response.body().string();
                           Log.d("TAG", "onResponse: string == "+string);
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
其他几种请求方式如下:
 Call<Modle> netDataWithModle = mNetInterface.getNetDataWithModle();
                     netDataWithModle.enqueue(new Callback<Modle>() {
                         @Override
                         public void onResponse(Call<Modle> call, Response<Modle> response) {
                             if (response.isSuccessful()){
                                  Modle body = response.body();
                                  Log.d("TAG", "onResponse: body" + body.toString());
                             }
                         }

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

                         }
                     });
或者:

 Call<Modle> netDataWithPage = mNetInterface.getNetDataWithPage("1");
                     netDataWithPage.enqueue(new Callback<Modle>() {
                         @Override
                         public void onResponse(Call<Modle> call, Response<Modle> response) {
                             if (response.isSuccessful()){
                                  Modle modle = response.body();
                                 Log.d("TAG", "onResponse:  body == "+modle.toString());
                             }
                         }

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

                         }
                     });
或者:

Map params = new HashMap();
                    params.put("page","2");
                    //params.put("count","2");
                     Call<Modle> netDataWithParams = mNetInterface.getNetDataWithParams(params);
                     netDataWithParams.enqueue(new Callback<Modle>() {
                         @Override
                         public void onResponse(Call<Modle> call, Response<Modle> response) {
                             if (response.isSuccessful()){
                                  Modle modle = response.body();
                                 Log.d("TAG", "onResponse: " +modle.toString());
                             }
                         }

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

                         }
                     });
或者:

  Call<ResponseBody> pathCall = mNetInterface.getNetDataWithPath("image");
                    pathCall.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response.isSuccessful()){
                                try {
                                    Log.d("TAG", "onResponse:  "+response.body().string());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

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

                        }
                    });
更多请看:

http://blog.csdn.net/duanyy1990/article/details/52139294









  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值