关于Retrofit基本实例讲解,让你醍醐灌顶

项目开发采用的网络框架选择retrofit,它在网络框架上排行领先地位,详情查看  https://github.com/square/retro

一、介绍:

1、Square公司为Android开源的类型安全的Http客户端
2、底层基于OkHttp,使用OkHttp进行请求
3、将java API的定义转换为interface形式
4、使用annotation描述http请求
5、支持配置json解析器

二、添加依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

 三、创建Retrofit实例对象

//1初始化Retorfit对象
retrofit = new Retrofit.Builder()
        //设置服务器主机地址,非常注意:BaseUrl必须以/结尾,否则报错
        //注意ip地址请设置为你自己的
        .baseUrl("http://192.168.2.155:8080/apitest/")
        //设置Gson为json的转换器
        .addConverterFactory(GsonConverterFactory.create())
        .build();

 四、定义业务逻辑接口:

public interface RetrofitInterface {
    /**
     * 定义了一个获取用户信息的业务方法,并且通过注解的方式
     * 指定了方法调用的时候所请求的url路径
     */
    @GET("test")
    Call<UserInfo> getUserInfo();
}

 五、创建接口实例对象:

//创建业务接口类实例对象,create方法内部实际上是用动态代理的方式帮助我们创建了实力对象
anInterface = retrofit.create(RetrofitInterface.class);

 六、获取业务方法调用对象,并进行请求:

public void get() {
    //1.得到请求的封装对象,包含注解的信息,就是url和参数信息
    Call<RetrofitInterface.UserInfo> call = anInterface.getUserInfo();
    //2.执行异步请求对象
    call.enqueue(new Callback<RetrofitInterface.UserInfo>() {
        @Override
        public void onResponse(Call<RetrofitInterface.UserInfo> call, Response<RetrofitInterface.UserInfo> response) {
            //1.得到结果
            RetrofitInterface.UserInfo userInfo = response.body();
            tvResult.setText(userInfo.toString());
        }
        @Override
        public void onFailure(Call<RetrofitInterface.UserInfo> call, Throwable t) {
        }
    });
}

七、以上就是关于retrofit请求的完整过程,接下来讲解一下retrofit的url注解处理,此处讲解五种注解的形式包含@Get,@Post,@Path,@Query ,@QueryMap
1、采用@Get注解来处理请求的url
      1.1
       @GET("test")
       Call<UserInfo> getUserInfo();

     1.2  使用ResponseBody来接收流的数据,比如下载文件
      @GET("image")
       Call<ResponseBody> getImage();


2、采用@Post注解来处理请求提交key-value数据
       2.1
       @FormUrlEncoded    //配置请求体参数进行url编码
       @POST("login")
       Call<Login> postLogin(@Field("username") String username,@Field("password") String password)

      2.2 使用@Post注解进行post请求,提交json数据
       @POST("login")
       Call<Login> postLogin(@Body LoginBody body)

      2.3使用@Muptipart和@Part或者@PartMap封装多块请求体
       @Multipart
       @POST("uploadMulti")
       Call<UploadResult> upload(@part("file") RequestBody);
      //或者使用@PartMap
       Call<UploadResult> upload(@partMap Map<String, RequestBody> map);

3、采用@Path注解来处理url路径不固定的需求
      @GET("test/{msg}")
      Call<Stu> getOrder(@Path("order")String order);

4、使用@Query注解来替换url后面跟的参数
        @GET("test")
       Call<Stu> getUser(@Query("id")String id);

5、使用@QueryMap来替换多个查询参数
       @GET("test")
       Call<Stu> login(@QueryMap Map<String ,String> map);

八、关于调用tomcat服务接口文档的说明  

  服务器主机

String url = "http://192.168.2.155:8080/apitest/";

获取json数据测试接口

  • 路径: /test
  • 返回数据:

    {"nickname":"俊哥!","name":"dance","age":"25","gender":"male"}
    

获取json数组测试接口

  • 路径:/list
  • 返回数据:

    [{"age":11,"name":"小明"},{"age":21,"name":"小红"},{"age":33,"name":"小王"}]
    

获取图片测试接口

  • 路径:/image
  • 返回数据:流

延时返回json数据测试接口

  • 说明:Server的响应会延时5秒钟
  • 路径: /delay
  • 返回数据:

    {"nickname":"俊哥!","name":"dance","age":"25","gender":"male"}
    

登录测试接口

  • 请求方式:Post
  • 路径: /login
  • 请求字段说明:
    • username:用户名,必须
    • password:密码,必须
  • 返回数据:

    {"username":"俊哥","usertoken":"6e416e5f-67a8-445f-a18a-1d8257f3fa07","password":"111"}
    

提交json对象接口

  • 请求方式:Post
  • 路径: /postJson
  • 请求字段说明: json对象
  • 返回数据:

    {"json":{"city":"北京","year":"2016"}}
    

上传单个文件测试接口

  • 请求方式:Post
  • 路径: /upload
  • 请求字段说明:
    • file:上传的File,必须
  • 返回数据:

    {"msg":"上传成功"}
    

批量上传文件测试接口

  • 请求方式:Post
  • 路径: /uploadMulti
  • 请求字段说明:
    • file:上传的File,必须
  • 返回数据:

    {"msg":"上传成功"}
    

九、总结
关于本demo有实例可下载包含get请求,post请求,上传下载的业务逻辑操作,借助tomcat开启服务,将apitest.war文件放到tomcat的此路径下  D:\download\apache-tomcat-8.0.33\webapps,再点击startup.bat双击打开即可调试运行数据。此demo下载路径:https://download.csdn.net/download/lou_liang/10784884

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值