关于Retrofit2.0Get和Post请求的简单使用(小白适用)

来源:互联网 发布:经典文学书籍推荐知乎 编辑:程序博客网 时间:2024/06/05 21:07

1.Get请求

导包什么的就不说了,首先实例化一个Retrofit类,然后使用构建者模式配置url之类的简单的东西

Retrofit retrofit = new Retrofit.Builder()        .baseUrl("http://120.27.23.105/")        .addConverterFactory(GsonConverterFactory.create())        .build();
在这里要注意的是baseurl里面的请求地址最后要以"/"结尾.
接下来就是需要创建一个接口类,在这个接口里面写一些Get请求所需要的参数
public interface ApiInterface {    @GET("user/getUserInfo")    Call<Repo> getDataInfo(@Query("uid") String uid);}
我用的请求地址的完整的应该是
http://120.27.23.105/user/getUserInfo?uid=**
这样的,但Retrofit要求我们必须要拆成上面这个样,我能怎么办,我也很绝望...
然后
Call<Repo> getDataInfo(@Query("uid") String uid);
getDataInfo是自定义的一个方法名,等会会用到,名字可以随便起,括号中的参数可以写多个
在这里面,就是用来写一些关于请求是需要用到的参数,结合上面完整的请求地址,不是智障的应该都恩那个看懂
这样  接口类就写好了
然后我们还需要创建一个bean类去接收请求下来的数据,这一点我建议使用gsonformat工具直接生成一个bean类
在Retrofit对象的下面
  ApiInterface apiInterface = retrofit.create(ApiInterface.class);
进行这样的操作,然后在进行
   Call<Repo> dataInfo = apiInterface.getDataInfo("100");
这样的操作 那个100就是uid,getDataInfo就是在接口类里面自定义的那个方法名
最后再
  dataInfo.enqueue(new Callback<Repo>() {            @Override            public void onResponse(Call<Repo> call, Response<Repo> response) {                //这里就可以做请求成功之后的事啦            }            @Override            public void onFailure(Call<Repo> call, Throwable t) {            }        });
一个Get请求就结束了,至于post请求,就是在接口类中
 @POST("user/getUserInfo")    @FormUrlEncoded    Call<Repo> getPost (@FieldMap Map<String,String> map);
然后在主类中实例化一个map集合,将参数put上去
Map<String, String> map = new HashMap<>();  map.put("uid", "100");
然后就是一样的套路
 Call<Repo> post = apiInterface.getPost(map);        post.enqueue(new Callback<Repo>() {            @Override            public void onResponse(Call<Repo> call, Response<Repo> response) {                System.out.println(response.body().msg + "+++++++++");            }            @Override            public void onFailure(Call<Repo> call, Throwable t) {            }        });

呃,就写到这里,已经虚脱了