GenweiWu / Blog

个人技术能力提升
MIT License
4 stars 0 forks source link

retrofit2 #85

Open GenweiWu opened 2 years ago

GenweiWu commented 2 years ago

常见的4种添加header方式

https://blog.csdn.net/SilenceOO/article/details/77460607

针对单个接口添加header

public interface ApiService {  
    @Headers({
        "Accept: application/json",
        "User-Agent: YourAppName"
    })
    @GET("/data/{user_id}")
    Call<Data> getData(@Path("user_id") long userId);
}

针对所有请求添加header,但是希望针对url选择是否添加对应header

https://stackoverflow.com/a/37823425

public interface MyApi {
    @POST("register")
    @HEADERS("@:NoAuth")
    Call<RegisterResponse> register(@Body RegisterRequest data);

    @GET("user/{userId}")
    Call<GetUserResponse> getUser(@Path("userId") String userId);
}
@HEADERS({
    "@: NoAuth",
    "@: LogResponseCode"
})
new OkHttpClient.Builder().addInterceptor(new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        List<String> customAnnotations = request.headers().values("@");

        // do something with the "custom annotations"

        request = request.newBuilder().removeHeader("@").build();
        return chain.proceed(request);
    }
});
GenweiWu commented 2 years ago

delete方法不能有body

public interface ImageService {
    @DELETE("api/v1/attachment")
    Call<BaseResponse> delete(@Body DeleteModel deleteModel);
}

解决方法

https://stackoverflow.com/q/41509195

@HTTP(method = "DELETE", path = "api/v1/attachment", hasBody = true)
Call<ResponseBody> getData(@Body DeleteModel deleteModel);
GenweiWu commented 1 year ago

访问外网url,连接超时,要配置代理服务器

// proxyHost类似a.b.com不要加上http://a.b.com
java.net.Proxy proxy = new Proxy(Proxy.Type.HTTP,  new InetSocketAddress(proxyHost, proxyPort));
OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();

Retrofit.Builder builder = new Retrofit.Builder().client(client);
Retrofit retrofit = builder.build();
GenweiWu commented 5 months ago

使用formdata实现上传文件

  1. @Part要搭配Multipart使用
  2. MultipartBody.Part对应的@Part不能有name ,改到 MultipartBody.Part.createFormData 这里添加
    
    @Multipart
    @POST("user/updateprofile")
    Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
    @Part("full_name") RequestBody fullName,
    @Part MultipartBody.Part image,
    @Part("other") RequestBody other);

//pass it like this File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody requestFile = RequestBody.create(MultipartBody.FORM, file);

// MultipartBody.Part is used to send also the actual file name MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request RequestBody fullName = RequestBody.create(MultipartBody.FORM, "Your Name");

service.updateProfile(id, fullName, body, other);

GenweiWu commented 4 months ago

308重定向

遇到一个post请求,308重定向了;如何在代码中进行兼容处理?

方案1:失败了

OkHttpClient client = new OkHttpClient.Builder()
                .followRedirects(true)
                .build();

分析后发现,只支持get或head方法的重定向

https://github.com/square/okhttp/issues/936#issuecomment-266430151

方案2(目前推荐)

public Response post(String url, String content) throws IOException {
        RequestBody body = RequestBody.create(PROTOCOL, content);

        Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
        Request request = requestBuilder.build();
        Response response = this.client.newCall(request).execute();

        if(response.code() == 307) {
            String location = response.header("Location");
            return post(location, content);
        }

        return response;
    }