java - How to add headers to OkHttp request interceptor? -
i have interceptor add okhttp client:
public class requesttokeninterceptor implements interceptor { @override public response intercept(chain chain) throws ioexception { request request = chain.request(); // here we'll try refresh token. // retrofit call // after succeed we'll proceed our request response response = chain.proceed(request); return response; } }
how can add headers request in interceptor?
i tried making mistake , lose request when creating new request:
public class requesttokeninterceptor implements interceptor { @override public response intercept(interceptor.chain chain) throws ioexception { request request = chain.request(); request newrequest; try { log.d("addheader", "before"); string token = tokenprovider.getinstance(mcontext).gettoken(); newrequest = request.newbuilder() .addheader(headerscontract.header_authonrization, o_auth_authentication + token) .addheader(headerscontract.header_client_id, client_id) .build(); } catch (exception e) { log.d("addheader", "error"); e.printstacktrace(); return chain.proceed(request); } log.d("addheader", "after"); return chain.proceed(newrequest); } }
note that, know can add header when creating request this:
request request = new request.builder() .url("https://api.github.com/repos/square/okhttp/issues") .header("user-agent", "okhttp headers.java") .addheader("accept", "application/json; q=0.5") .addheader("accept", "application/vnd.github.v3+json") .build();
but doesn't fit needs. need in interceptor.
finally, added headers way:
@override public response intercept(interceptor.chain chain) throws ioexception { request request = chain.request(); request newrequest; newrequest = request.newbuilder() .addheader(headerscontract.header_authonrization, o_auth_authentication) .addheader(headerscontract.header_x_client_id, client_id) .build(); return chain.proceed(newrequest); }
Comments
Post a Comment