compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2'
//自定义接口 存放uri串
public interface Getnet { //retrofit要求有一个根地址,此处我们用主机域名作为根地址,/严格要求必须有 //http://www.yulin520.com/a2a/impressApi/news/mergeList?pageSize=10 你要解析的uri串 public static String net="http://www.yulin520.com/a2a/"; }
//接口为 网络请求的方式
public interface TestService { //User 为uri串 转换的bean对象 //impressApi/news/mergeList?pageSize=10&page=10为 @GET("impressApi/news/mergeList?pageSize=10&page=10") Call<User> getUser(); @GET("impressApi/news/mergeList?pageSize=10") Call<User> getUsermap(@QueryMap Map<String,String> map); @POST("impressApi/news/mergeList?pageSize=10") @FormUrlEncoded Call<User> postUser(@Field("page") String id); @POST("impressApi/news/mergeList?pageSize=10") @FormUrlEncoded Call<User> postUsermap(@FieldMap Map<String,String> map); }
//工具包 解析json串的时候用
public class Util { private volatile static Util util=null; private Util(){ } public static Util getmInstance(){ if (util==null){ synchronized (Util.class){ if (util==null){ util=new Util(); } } } return util; } public Testservice getnetjson(String uri){ Retrofit retrofit = new Retrofit.Builder().baseUrl(uri) .addConverterFactory(GsonConverterFactory.create()) .build(); Testservice testservice = retrofit.create(Testservice.class); return testservice; } }
//解析json串的代码
Map<String,String> map=new HashMap<>(); map.put("page","10"); //Getnet.net 为前半截字符串 TestService testService = Util.getnetjson(Getnet.net); //调用接口里面的方法 testService .getUsermap(map).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //body为解析出来的bean对象 User body = response.body(); }
//失败的方法 @Override public void onFailure(Call<User> call, Throwable t) { } });
参考 http://blog.csdn.net/carson_ho/article/details/73732076