vendredi 18 septembre 2015

OkHttp RequestBody returning wrong content length

I have this app where I use OkHttp RequestBody to perform network requests with body, but the content length being returned is plain wrong. As an example of the problem, there is this case:

    public static RequestBody createNewTokenBody(final String redirectUri, final String
        code,
                                             final String clientId, final String
                                                     clientSecret) {

    final byte[] requestBody = "bunchofcharsthatshouldgointhebody".getBytes(Charset.forName("UTF-8"));

    final RequestBody ret = RequestBody.create(MediaType.parse(MEDIA_TYPE), requestBody, 0,
            requestBody.length);

    try {
        Log.d("debug", "Request body length to return: " + ret.contentLength());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ret;
}

So this will print "Request body length to return : 33". However, when the request this body is attached to is captured by the interceptor below:

    client.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(final Chain chain) throws IOException {
            final Request request = chain.request();

            final RequestBody body = request.body();
            if (body != null) {
                Log.d("debug", "REQUEST BODY LENGTH: " + body.contentLength());
            }

            return chain.proceed(request);
        }
    });

"REQUEST BODY LENGTH: 2" is logged instead, regardless of the content that I specified. Needless to mention that this completely screws up the request as the body is not fully read. Does anybody know the reason behind this behavior?



from Newest questions tagged java - Stack Overflow http://ift.tt/1FRgQUD
via IFTTT

Aucun commentaire:

Enregistrer un commentaire