반응형
OkHttp 요청 인터셉터에 헤더를 추가하는 방법은 무엇입니까?
내 OkHttp 클라이언트에 추가하는이 인터셉터가 있습니다.
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Here where we'll try to refresh token.
// with an retrofit call
// After we succeed we'll proceed our request
Response response = chain.proceed(request);
return response;
}
}
인터셉터에서 요청에 헤더를 추가하려면 어떻게해야합니까?
나는 이것을 시도했지만 실수를하고 새 요청을 만들 때 내 요청을 잃어 버립니다.
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);
}
}
다음과 같은 요청을 만들 때 헤더를 추가 할 수 있음을 알고 있습니다.
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();
그러나 그것은 내 필요에 맞지 않습니다. 인터셉터에 필요합니다.
마지막으로 다음과 같이 헤더를 추가했습니다.
@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);
}
당신은 이렇게 할 수 있습니다
private String GET(String url, Map<String, String> header) throws IOException {
Headers headerbuild = Headers.of(header);
Request request = new Request.Builder().url(url).headers(headerbuild).
build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Retrofit 라이브러리를 @Header
사용하는 경우 Interceptor를 사용하지 않고 주석을 사용 하여 헤더를 API 요청에 직접 전달할 수 있습니다 . 다음은 Retrofit api 요청에 헤더를 추가하는 방법을 보여주는 예입니다.
@POST(apiURL)
void methodName(
@Header(HeadersContract.HEADER_AUTHONRIZATION) String token,
@Header(HeadersContract.HEADER_CLIENT_ID) String token,
@Body TypedInput body,
Callback<String> callback);
도움이 되었기를 바랍니다.
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
There is yet an another way to add interceptors in your OkHttp3 (latest version as of now) , that is you add the interceptors to your Okhttp builder
okhttpBuilder.networkInterceptors().add(chain -> {
//todo add headers etc to your AuthorisedRequest
return chain.proceed(yourAuthorisedRequest);
});
and finally build your okHttpClient from this builder
OkHttpClient client = builder.build();
Faced similar issue with other samples, this Kotlin class worked for me
import okhttp3.Interceptor
import okhttp3.Response
class CustomInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) : Response {
val request = chain.request().newBuilder()
.header("x-custom-header", "my-value")
.build()
return chain.proceed(request)
}
}
참고URL : https://stackoverflow.com/questions/32196424/how-to-add-headers-to-okhttp-request-interceptor
반응형
'IT Share you' 카테고리의 다른 글
터치를 통해 UIViews 아래에 전달 (0) | 2020.11.19 |
---|---|
다른 사용자의 힘내 풀 명령 (0) | 2020.11.19 |
포드 내에서 컨테이너 다시 시작 (0) | 2020.11.19 |
렌더링 된 HTML 페이지의 일부를 JavaScript로 인쇄하려면 어떻게합니까? (0) | 2020.11.19 |
추가 대신 Ajax 교체 (0) | 2020.11.19 |