Android-Retrofit示例

0. Thanks

Android Retrofit2 Post请求添加Json类型参数笔记

Retrofit2.0添加Header的方法总结

关于Retrofit网络请求URL中含有可变参数的处理

1. Header

  • 1)使用注解,Header是固定的
public interface ApiService {
    @Headers("Cache-Control: max-age=560000")
    @GET("/data")
    Call<List<Data>> getData();
}
  • 2)使用注解,添加多个固定的Header
public interface ApiService {
    @Headers({
        "Accept: application/vnd.yourapi.v1.full+json",
        "User-Agent: YourAppName"
    })
    @GET("/data/{user_id}")
    Call<Data> getData(@Path("user_id") long userId);
}
  • 3)使用注解的方式,header参数每次都不同,动态添加header
public interface ApiService {
    @GET("/data")
    Call<List<Data>> getData(@Header("Content-Range") String contentRange);
}
  • 4)使用注解,动态添加多个Headers
public interface ApiService {
    @GET("/data")
    Call<ResponseBody> list(@HeaderMap Map<String, String> headers);
}
  • 5)在拦截器里面,代码动态添加Header
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();
        Request request = original.newBuilder()
            .header("User-Agent", "YourAppName")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();
        return chain.proceed(request);
    }
}
OkHttpClient httpClient = client.build();
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(Constant.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(httpClient)
    .build();

2. Get

假设BaseURL为https://192.168.1.101/api/

普通的请求:https://192.168.1.101/api/MovieList

@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList();

URL中参数有变:https://192.168.1.101/api/MovieList/{2018},{2018}是用户ID,会变化

@GET("MovieList/{movieId}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId );

URL中参数有变:https://192.168.1.101/api/MovieList/{2018}/{comedy},后面的两个参数会变

@GET("MovieList/{movieId}/{type}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId ,@Path("type") String type);

URL中参数在问号后,即是参数拼接在URL后面:https://192.168.1.101/api/MovieList?movieId=10011&type=3

@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList(@Query("movieId") String movieId,@Query("type") int type);

URL中参数在问号后,既是参数拼接在URL后面,而且参数不固定:https://192.168.1.101/api/MovieList?movieId=10011&type=4&year=2013&......

@GET("MovieList")
Observable<ResultEntity<MovieEntity>> getMovieList(@QueryMap Map<String ,Object> map);

3. POST

假设BaseURL为https://192.168.1.101/api/

url中含有可变参数,post的数据只有一个type:https://192.168.1.101/api/MovieList/2018

@FormUrlEncoded
@POST("MovieList/{movieId}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId, @Field("type") String type);

url中含有可变参数、问号之后需要加入token,post的数据为一个对象(json串):

https://192.168.1.101/api/MovieList/2018?token=4654551321563132fasd5645ds3

@POST("MovieList/{movieId}")
Observable<ResultEntity<MovieEntity>> getMovieList(@Path("movieId") String movieId,
                                                   @Query("token") String token,
                                                   @Body MovieEntity entity);

POST文件上传

API描述

Hy_Base_Url_Upload = "http://abc/api/upload/image"
参数1:sn , 设备号
参数2:description , 图片的描述
参数3:scan_image , 图片文件

接口声明如下

public interface Hy {
    @Multipart
    @POST("image")
    Observable<String> postFruitImg(
        @Query("sn") String sn,
        @Part("description") RequestBody description,
        @Part MultipartBody.Part file);
}

代码调用如下

/**
 * 上传文件
 * @param file 文件
 * @return bean
 */
public Observable<String> uploadImg(File file) {
    //构建API接口
    Retrofit retrofit1 = new Retrofit.Builder()
            .baseUrl(Common.Hy_Base_Url_Upload)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
    Common.Hy hy = retrofit1.create(Common.Hy.class);
    // 创建 RequestBody,用于封装构建RequestBody
    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    // MultipartBody.Part  和后端约定好Key,这里的partName是用image
    MultipartBody.Part body = MultipartBody.Part.createFormData("scan_image", file.getName(), requestFile);
    // 添加描述
    String descriptionString = "hello, 这是文件描述";
    RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
    // 执行请求
    return hy.postFruitImg(HyUtils.getSNCode(),description,body);
}

Post文件上传,还需要额外传递一些key-value

@POST("/system/update_pic.php")
@Multipart
Observable<String> uploadHeadPic(@Part MultipartBody.Part part,
        @Part("timestamp") String time,
        @Part("rand") String rand,
        @Part("check") String check,
        @Part("uid") String uid,
        @Part("is_robot") String isRobot,
        @Part("platform") String platform);

接口如上,@Part是,当声明为:@Multipart的时候,key-value的key关键字。
其他参数照样传递,而@Part MultipartBody.Part part要注意一下:

// 创建 RequestBody,用于封装构建RequestBody
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), local);
// MultipartBody.Part  和后端约定好Key,这里的partName是用image
MultipartBody.Part body = MultipartBody.Part.createFormData("pic", "headPic", requestFile);

请求的代码如下:

Retrofit retrofit1 = new Retrofit.Builder()
        .baseUrl(baseServer + ":" + port)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();
HttpProtocolContract httpProtocolContract = retrofit1.create(HttpProtocolContract.class);
long time = CoreManager.getInstance().getWebTimeSecond();
String rand = "0123456789abcdefghijklmnopqrstouwxyz" + time + System.nanoTime();
String check = StringUtils.changeTOLowerCase(EncryptUtils.encryptSHA1ToString(session + "0" + rand + time));
// 创建 RequestBody,用于封装构建RequestBody
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), local);
// MultipartBody.Part  和后端约定好Key,这里的partName是用image
MultipartBody.Part body = MultipartBody.Part.createFormData("pic", "headPic", requestFile);
// 执行请求
return httpProtocolContract.uploadHeadPic(body,String.valueOf(time),rand,check,String.valueOf(uid),"0","0")
        .observeOn(Schedulers.io())
        .map(s -> {
            LogUtils.i(TAG,"uploadUserHeadPic:"+s);
            return 0;
        });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,534评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 178,909评论 25 709
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 34,638评论 18 399
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,261评论 6 342
  • 合院基友湖记载着一个故事,关于一名困情男子投水的传说。我想,深情即是一桩悲剧,必得以死来句读,而这种死也是最纯洁的...
    季夏冰语阅读 559评论 0 0

友情链接更多精彩内容