Get the Charset of the HTTP response of the provided httpResponse - Android Network

Android examples for Network:HTTP Response

Description

Get the Charset of the HTTP response of the provided httpResponse

Demo Code


import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import android.annotation.SuppressLint;
import android.os.Build;
import android.text.TextUtils;

public class Main{
    /**//from   w  w w  .j  a v a2s .c o  m
     * Get the {@link Charset} of the HTTP response of the provided httpResponse
     * @param httpResponse that was queried on the server
     * @param defaultCharset to use if the server sets no Charset or it's not found locally
     * @return The Charset of specified by the server, if found locally, otherwise {@code defaultCharset}
     */
    public static Charset getInputCharset(HttpResponse httpResponse,
            Charset defaultCharset) {
        Charset readCharset = defaultCharset;
        String contentType = httpResponse.getContentType();
        if (!TextUtils.isEmpty(contentType)) {
            MediaType type = MediaType.parse(contentType);
            if (null != type && null != type.charset())
                readCharset = type.charset();
        }
        return readCharset;
    }
}

Related Tutorials