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> getData();
}
  • 2)使用注解,添加多个固定的Header
public interface ApiService {
    @Headers({
        "Accept: application/vnd.yourapi.v1.full+json",
        "User-Agent: YourAppName"
    })
    @GET("/data/{user_id}")
    Call getData(@Path("user_id") long userId);
}
  • 3)使用注解的方式,header参数每次都不同,动态添加header
public interface ApiService {
    @GET("/data")
    Call> getData(@Header("Content-Range") String contentRange);
}
  • 4)使用注解,动态添加多个Headers
public interface ApiService {
    @GET("/data")
    Call list(@HeaderMap Map 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> getMovieList();

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

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

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

@GET("MovieList/{movieId}/{type}")
Observable> 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> 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> getMovieList(@QueryMap Map 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> 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> 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 postFruitImg(
        @Query("sn") String sn,
        @Part("description") RequestBody description,
        @Part MultipartBody.Part file);
}

代码调用如下

/**
 * 上传文件
 * @param file 文件
 * @return bean
 */
public Observable 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 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;
        });

你可能感兴趣的:(Android-Retrofit示例)