当前位置:网站首页>Retrofit2.0 method summary of adding header

Retrofit2.0 method summary of adding header

2022-06-09 23:59:00 Sharp surge

One 、 Using annotations
1. Add a single header

public interface ApiService {
    @Headers("Content-Type: application/javascript")
    @GET("/data")
    Call<List<AddressBean>> getData();
}


2. Add multiple header

public interface ApiService {
    @Headers({
            "Content-Type: application/javascript",
            "User-Agent: YourAgent"
    })
    @GET("/data/{user_id}")
    Call<List<AddressBean>> getData();
}

3. Dynamic addition header

public interface ApiService {
    @GET("/data")
    Call<List<AddressBean>> getData(@Header("Content-Range") String contentRange);
}


4. Dynamically add multiple header

@GET("/search")
Call<ResponseBody> list(@HeaderMap Map<String, String> headers);

1. Post Add a single header

@POST("api/sys/getPermissions")
Observable<ResponseBean<PermissionsBean>> getPermissions(@Query("__token") String token);


2.post Add fixed multiple header
 

@POST("api/sys/getPermissions")
 @Headers({"Content-Type:application/x-www-form-urlencoded",
            "Authorization:Basic VmJyZjJNU1FxejhBVlhzMmajhETkJV"})
 Observable<TokenBean> getSsoToken();


Two 、 If you want to add a global header, You need to add header
 

   /**
     *  Request interceptor 
     */
    private class RequestInterceptor implements Interceptor {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
 
            Request oldRequest = chain.request();
            Request request = oldRequest.newBuilder()
                    .headers(Headers.of(getHeaders()))// Injection header information 
                    .build();
            logRequest(request);
            return logResponse(chain.proceed(request));
        }
    }
 
    /**
     *  Get header information 
     */
    private Map<String, String> getHeaders() {
        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("Cookie","jeeplus.session.id");
        return headersMap;
    }


————————————————
Copyright notice : This paper is about CSDN Blogger 「 Pearl of Tianlan 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/u012693479/article/details/99645085

原网站

版权声明
本文为[Sharp surge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206092322122314.html