0

I'm trying to append an Api key into the body of my request using an interceptor. I've tried various ways, none of them works..

URL: https://someapi.com/api/stories/

METHOD: POST

HEADERS: Accept: application/json

INPUT: {"key": ""}

@Provides @Singleton public Interceptor interceptor(NetworkUtils networkUtils) { return chain -> { Request originalRequest = chain.request();

        RequestBody requestBody = networkUtils.createBody();
        String postBodyString = networkUtils.bodyToString(requestBody);
        Request.Builder builder = originalRequest.newBuilder();
        postBodyString += ((postBodyString.length() > 0) ? "&" : "") + networkUtils.bodyToString(requestBody);
        originalRequest = builder.
                post(RequestBody.create(MediaType.parse(Constants.NETWORKING_HEADER.CONTENT_TYPE), postBodyString)).build();
        return chain.proceed(originalRequest);
    };
}


public RequestBody createBody() {
    return new FormBody.Builder()
            .add(Constants.NETWORKING_HEADER.KEY, Constants.NETWORKING_HEADER.API_KEY).build();
}

public String bodyToString(final RequestBody request) {

    try {
        final RequestBody copy = request;
        final Buffer buffer = new Buffer();
        if (copy != null) {
            copy.writeTo(buffer);
        } else {
            return "";
        }
        return buffer.readUtf8();
    } catch (final IOException e) {
        String message = "Did not work";
        Timber.d(message);
        return message;
    }
}

1 Answers1

0

Possible duplicate of Retrofit2: Modifying request body in OkHttp Interceptor

The last answer by @Debanjan offers a good solution, covers both application/json as well as form data.

Mohamed Khaled
  • 139
  • 1
  • 7