Regrofit 网络请求库学习记录

来源:互联网 发布:爱的算法 pdf 编辑:程序博客网 时间:2024/06/07 15:01

1 添加依赖(看了半天 没几个文章写依赖的地址,最后去github才看到)

     compile 'com.squareup.retrofit2:retrofit:2.1.0'
     github地址 :  https://github.com/square/retrofit
2 简单实现一个返回String的示例

    首先是服务器 :  定义一个接口,就是反回一个 "hello world" 的文本,路径是"http://192.168.10.117:8081/test.txt"

    手机中 :  先定义一个接口 

    public interface HttpService {        @GET("test.txt")        Call<String> getMessage(@Query("testParam") String testParam);    }
    其中, getMessage方法对应服务器的test.txt的接口地址相对路径,这个HttpService里边可以定义多个方法,分别对应不同的服务器接口;

    @GET("test.txt")  : 表示get方法请求,里边的"test.txt"为绝对路径 ; 其他的还有@POST @PUT 等.. 

    @Query("testParams") : 表示上传的参数  key就是testParams ,value就是传入的值; 这里写上了只为学习,没什么用,因为服务器没有接受参数;

    然后, 创建一个Retrofit对象

    public static final Retrofit stringClient = new Retrofit.Builder().baseUrl("http://192.168.10.117:8081/")            .addConverterFactory(new Converter.Factory() {                public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {                    return new Converter<ResponseBody, Object>() {                        public String convert(ResponseBody value) throws IOException {                            return value.string();                        }                    };                }            }).build();
这里主要就是addConvertFactory方法,是一个转换,参数需要一个Converter.Factory对象,这个Converter.Factory是一个抽象类,里边有三个方法可以重写,这里只重写responseBodyConverter方法,表示将服务器反回的数据转换成什么,这里仅仅是转换成了String来对应HttpService的Call<String>的这个泛型返回值,网上看的都是使用GsonConverterFactory直接转换成对象;



然后就万事俱备,可以请求服务器了,这里请求服务器和OKHttp差不多,有同步和异步两种方式,这里展示一下异步的方式

        HttpService service = stringClient.create(HttpService.class);        Call<String> call = service.getMessage("我是没用的测试参数");        call.enqueue(new Callback<String>() {            public void onResponse(Call<String> call, Response<String> response) {                if (response.isSuccessful()) {                    String bodyString = response.body();                    Toast.makeText(RetrofitActivity.this, bodyString, Toast.LENGTH_SHORT).show();                } else {                    onFailure(call, null);                }            }            public void onFailure(Call<String> call, Throwable t) {                String msg = (t==null)?"" : t.getLocalizedMessage();                Toast.makeText(RetrofitActivity.this, "error"+t, Toast.LENGTH_SHORT).show();            }        });


@Path 注解 , 表示参数作为url路径的一部分 , 如果下面的path参数传递的是"hello" ,baseUrl是http://a.com/ , 那么完整路径就是 http://a.com/hello/get

 @GET("{test}/get") Call<String> getMessage2(@Path("test") String path);


      

 感觉这东西如果不是restful风格的url, 还不如直接用okhttp自己封装, 哪有说的那么好;

1 0
原创粉丝点击