开源地址:https://github.com/square/retrofit
<=1.9.0 用法 1、在build.gradle中添加依赖:
1 compile 'com.squareup.retrofit:retrofit:1.9.0'
2、创建网络接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 package com.linwoain.testexception;import com.linwoain.retrofit.bean.Person;import retrofit.Callback;import retrofit.http.GET;import retrofit.http.Query;public interface RestService { @GET("/api.php") void getMsg (@Field("name") String name, Callback<Person> cb) ; }
注意:在使用Field注解的时候,自己碰到一个大坑,使用@POST注解方法然后用@Query注解参数,可以正常使用却会导致乱码,搞了一下午。还用以前的xUtils正常情况与出乱码情况抓包分析,如下
发现Query注解参数,会直接在url后面传参,无论是否post方法,坑爹的是这种服务器也能解析到,但是中文就会乱码。使用Field的情况如下:
无乱码,正常了。
其中Person对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 package com.linwoain.testexception;public class Person { int age; String name; String sex; String time; String msg; public int getAge () { return age; } public void setAge (int age) { this .age = age; } public String getName () { return name; } public void setName (String name) { this .name = name; } public String getSex () { return sex; } public void setSex (String sex) { this .sex = sex; } public String getDate () { return time; } public void setDate (String date) { this .time = date; } public String getMsg () { return msg; } public void setMsg (String msg) { this .msg = msg; } }
3、创建service对象:
1 2 3 RestAdapter adapter = new RestAdapter.Builder().setEndpoint("https://www.linwoain.com" ).setConverter(new GsonConverter(new Gson())).build(); service = adapter.create(RestService.class);
4、调用接口里的方法并实现回调:
1 2 3 4 5 6 7 8 9 10 11 12 service.getMsg("linwoain" , new Callback<Person>() { @Override public void success (Person person, Response response) { LLogUtils.i(GsonUtil.toGson(person)); ToastUtil.show(person.getDate()); } @Override public void failure (RetrofitError error) { error.printStackTrace(); } });
上方代码,可以直接在ui线程中调用,因为service已经做了异步处理。
tips:
新版本2.0.0-beta1貌似与原版本相差较大!以上代码不能通用!