关于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) { } });
呃,就写到这里,已经虚脱了
阅读全文
0 0
- 关于Retrofit2.0Get和Post请求的简单使用(小白适用)
- 使用retrofit2.0实现网络请求post和get请求
- Retrofit2的get请求和post请求
- Retrofit2的get请求和post请求
- Retrofit2.0的get post请求简单数据
- Retrofit2.0的get请求和post请求(入门级)
- [Android] Retrofit2.0 GET和POST方式请求
- 关于 GET 和 POST 请求的简单示例
- 简单的POST请求和get请求
- 关于Curl的get和post请求
- 关于 GET和POST请求的区别
- Rxjava2.0和Retrofit2.0结合使用(2)post请求
- 关于GET和POST请求
- 关于GET和POST请求
- retrofit2.0中使用okHTTP post get put 过滤请求内容或添加内容
- okgo简单的GET请求 和POST请求
- Android Retrofit2.0-post&get请求&文件上传&结合Rxjava
- 关于ajax原生的get请求和post请求
- [Java--常见排序算法]------堆排序 (Heap Sort)
- python的文件处理
- navicat for java设计表时长度的作用
- logstash日志分析的配置和使用
- ubantu install mongo
- 关于Retrofit2.0Get和Post请求的简单使用(小白适用)
- 使用nnp_convolution_output return status==50,initial failed.
- jmeter
- Webservice工作原理及实例
- 文件的权限
- cxf webservice 调用 https
- spring autowired 标签
- 关于数组的使用
- 当小米MIX 2遇到iPhone X 你会怎么选?