Retrofit使用

添加gradle:

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

Retrofit是什么?

A type-safe HTTP client for Android and Java

这是官网对retrofit的介绍。

retrofix出自Square公司,是一个很好网络请求框架。看了源码之后,该框架满满的都是设计模式,满满的都是解偶,这个框架扩展性非常的强,膜拜啊。

Retrofit2 结构

retrofit2的包结构:

这里写图片描述

可以看到只有那么的几个类,因为retrofit把请求的任务交给了OkHttp。

retrofit2:

retrofix2.http:该包下定义了很多注解。通过这些注解来表明请求的方式是什么方式,URL怎么处理等。

常用的注解:
@GET():表示发送Get的请求。
@POST():表示Post请求。
@Query();发送请求配置一个参数
@QueryMap();发送请求配置多个参数。
@Multipart();表示发送MultiPart数据。
@Part();发送MultiPart数据时,通过该注解来定义每一个文件。
@PartMap();发送MultiPart数据时,通过该注解来定义多个文件。

Retrofit使用

我使用了聚合数据新闻的一个接口:

接口:http://op.juhe.cn/onebox/news/query
AppKey:ea2ee38eb5d582931b66e927eff35b24

定义一个接口NewsService:

public interface NewsServive {

    @GET("/onebox/news/query")
    Call<NewsInfo> newsListByGetMethod(@QueryMap Map<String,String> paramsMap);
}

使用retrofix发送请求这样定义一个接口就可以了,神奇吧。
注解说明:
@GET,表示发送一个get请求,值为请求地址(域名以后)。
@QueryMap:请求参数。也可以用@Query,这里我们有两个参数。写法为:

public interface NewsServive {

    @GET("/onebox/news/query")
    Call<NewsInfo> newsListByGetMethod(@Query("q") String q ,@Query("key") String key);
}

@Query注解的值,q,key是对应请求的字段名。

如果发送Post请求,把注解@GET改为@POST就可以了,@QueryMap和@Query注解的用法一样。

public interface NewsServive {

    @POST("/onebox/news/query")
    Call<NewsInfo> newsListByGetMethod(@QueryMap Map<String,String> paramsMap);
}
public interface NewsServive {

    @POST("/onebox/news/query")
    Call<NewsInfo> newsListByGetMethod(@Query("q") String q ,@Query("key") String key);
}

Activity:

public class TestRetrofixActivity extends AppCompatActivity {

    private final static String BASE_URL = "http://op.juhe.cn";
    private final static int REQ_OK = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_retrofix);
        reqServer();
    }

    private void reqServer() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)  //请求地址的域名
                .addConverterFactory(GsonConverterFactory.create())//把请求返回的数据解析我们关系的格式,这里我们通过Gson来解析返回的数据
                .client(new OkHttpClient())
                .build();

        NewsServive newsServive = retrofit.create(NewsServive.class);

        Map paramsMap =  getParamsMap();  //获取请求参数

        Call<NewsInfo> newsInfoCall = newsServive.newsListByGetMethod(paramsMap);

        //发送异步的请求
        newsInfoCall.enqueue(new Callback<NewsInfo>() {
            @Override
            public void onResponse(Call<NewsInfo> call, Response<NewsInfo> response) {

                NewsInfo newsInfo = response.body();
                if(newsInfo.getError_code() == REQ_OK){

                    for (NewsInfo.ResultBean info : newsInfo.getResult()){
                         Log.e("tag","-----> info = " + info.toString());
                     }

                }else{
                    Log.e("tag","----> reason = " + newsInfo.getReason());

                }

            }

            @Override
            public void onFailure(Call<NewsInfo> call, Throwable t) {
                Log.e("tag","-----> error = " + t.getMessage());

            }
        });

    }

    private Map getParamsMap() {

        Map<String,String> map = new HashMap<>();
        map.put("q","百度竞价");
        map.put("key","ea2ee38eb5d582931b66e927eff35b24");
        return map;
    }

}

可以看到retrofit使用起来非常的简单,就不过多解释了。

下面我们来看看,使用retrofit上传图片:

定义接口:

public interface ImageUploadSerivce {

    @Multipart
    @POST("/upload")
    Call<String> uploadImage(@Part("fileName") RequestBody image);
}

如果有多个文件需要上传,使用注解@PartMap,也可以使用多个@Part注解,如下:

public interface ImageUploadSerivce {
    @Multipart
    @POST("/upload")
    Call<String> uploadImage(@PartMap Map<String,RequestBody> params);
}

public interface ImageUploadSerivce {

    @Multipart
    @POST("/upload")
    Call<String> uploadImage(@Part("fileName") RequestBody image ,@Part("file2") RequestBody image2);

}

Activity:


public class ImageUploadActivity extends AppCompatActivity {

    private static final String BASE_URL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_upload);

        uploadImage();
    }

    private void uploadImage() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)  //请求地址的域名
                .addConverterFactory(GsonConverterFactory.create())//把请求返回的数据解析我们关系的格式,这里我们通过Gson来解析返回的数据
                .client(new OkHttpClient())
                .build();

        ImageUploadSerivce imageUploadSerivce = retrofit.create(ImageUploadSerivce.class);

        File file = new File("image.png");

        RequestBody imgBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);

        Call<String> call = imageUploadSerivce.uploadImage(imgBody);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {

                Log.d("tag","-------> response = " + response.message());
            }

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

                Log.d("tag","-------> error = " + t.getMessage());

            }
        });


    }
}

retrofit使用起来还是很简单的,就不多解释了。

如有什么问题,希望大家多多指正。谢谢。

END

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值