Android网络请求之Retrofit2(1)

前言:用了那么长时间的Retrofit现在纪录一下,这篇是简单的使用方法,后续会继续更新,本篇适合新手,老鸟可以给点意见

废话不多说,直接开撸

首先是引入所需要的包,别忘记点同步

implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'

1,将你的okhttp请求改造成java接口,用注解描述和配置网络请求参数,封装Url地址和网络数据请求

public interface ApiService{
        @GET("getAll")
        Call<ResponseBody> getAll(@Query("key") String key, @Query("consName") String consName, @Query("type") String type);
    }

这里以我的聚合接口为例说明一下

@GET-----表示的get请求(详情请看表1)

(“getAll”)里面的getAll-----表示的是请求的地址(也就是url后面加的地址,属于url的一部分),它和baseUrl组合起来就是全路径请求地址吗,例如URL=“http://web.juhe.cn:8080/constellation/”,请求的地址是getall,那么组合起来的全路径就是“http://web.juhe.cn:8080/constellation/getAll”

Call<Bean>里面的Bean-----表示的是咱们自定义的Bean类,也可以写成 ResponseBody,这个一般是在测试或者还不清楚返回的内容的时候使用,用它直接返回的是String形类型的数据

getAll-----表示的方法名,这个咱们可以自由定义方法名

@Query("key") String key-----@Query表示的是请求参数注解,(“key”)表示的是接口的请求参数字段,String不多说是参数类型,后面的key是字段的值(详情请看表2)

 表1请求方法注解

请求方法注解 说明
@GET get请求
@POST post请求
@PUT put请求
@DELETE delete请求
@PATCH patch请求,该请求是对put请求的补充,用于更新局部资源
@HEAD head请求
@OPTIONS options请求
@HTTP 通过注解,可以替换以上所有的注解,它拥有三个属性:method、path、hasBody

 表2请求参数注解

请求参数注解 说明
@Body 多用于Post请求发送非表达数据,根据转换方式将实例对象转化为对应字符串传递参数,比如使用Post发送Json数据,添加GsonConverterFactory则是将body转化为json字符串进行传递
@Filed 多用于Post方式传递参数,需要结合@FromUrlEncoded使用,即以表单的形式传递参数
@FiledMap 多用于Post请求中的表单字段,需要结合@FromUrlEncoded使用
@Part 用于表单字段,Part和PartMap与@multipart注解结合使用,适合文件上传的情况
@PartMap 用于表单字段,默认接受类型是Map<String,RequestBody>,可用于实现多文件上传
@Path 用于Url中的占位符
@Query 用于Get请求中的参数
@QueryMap 与Query类似,用于不确定表单参数
@Url 指定请求路径

 然后是服务请求url,由IP和端口组成,也就是咱们经常用的后台提供给我们的接口,切记接口后面加“/”因为后面还会拼接东西,不加的话会报错

public static final String Url="http://web.juhe.cn:8080/constellation/";

2,创建Retrofit实例

Retrofit retrofit=new Retrofit.Builder().baseUrl(Url).build();

这里注意的是前面的Bean如果是用的ResponseBody可以直接这样写,如果是自定义的Bean类的话需要加addConverterFactory(GsonConverterFactory.create())也就是Gson转换器

Retrofit retrofit=new Retrofit.Builder().baseUrl(Url).addConverterFactory(GsonConverterFactory.create()).build();

然后创建接口实例

ApiService apiService=retrofit.create(ApiService.class);

接下来就是调用了,调用接口中的方法

Call<ResponseBody> call=apiService.getAll("3e4d3cb8eb07d3b06e3f6a99ae34b1ee","双子座","today");

最后就是接收返回的结果

call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    System.out.println("666"+response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("33333"+call+"/n"+t.toString());
            }
        });

3,这是完整的代码,这里我直接在类中运行,比较懒

public class RetrofitText {
    //服务器请求的URL
    public static final String Url="http://web.juhe.cn:8080/constellation/";
    //定义接口
    public interface ApiService{
        @GET("getAll")
        Call<ResponseBody> getAll(@Query("key") String key, @Query("consName") String consName, @Query("type") String type);
    }

    public static void main(String[] args){
        getList();
    }
    public static void getList(){
        //创建Retrofit实例
        Retrofit retrofit=new Retrofit.Builder().baseUrl(Url).build();
        //创建接口实例
        ApiService apiService=retrofit.create(ApiService.class);
        //调用接口中的方法
        Call<ResponseBody> call=apiService.getAll("3e4d3cb8eb07d3b06e3f6a99ae34b1ee","双子座","today");
        //返回结果
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    System.out.println("返回的结果"+response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("33333"+call+"/n"+t.toString());
            }
        });
    }
}

运行完成得到的结果

{"date":20200810,"name":"双子座","QFriend":"水瓶座","color":"水蓝色","datetime":"2020年08月10日","health":"80","love":"70","work":"80","money":"60","number":4,"summary":"请调整你处理事情的方式,你是有机会朝目标前进的,但双子座很容易在略感困难的状况下改变方向,这种消极行为尽量避免,你才能在合适的时机有收获。作者:伦敦占星学院-不卉游泳的鱼","all":"80","resultcode":"200","error_code":0}

这篇先到这里,后续继续更新

猜你喜欢

转载自blog.csdn.net/lanrenxiaowen/article/details/107906623