覆盖java HttpUrlConnnection的HTTP标头

时间:2016-12-19 12:31:37

标签: java http-headers httpurlconnection

我试图覆盖HttpUrlConnection的Http Headers,以便将Accept-Language设置为特定值。然而,在测试它(对一个真实的网站),并使用Charles Proxy检查流量时,我得到了Accept-Language的两个Http Header值 - 我强制的一个和另一个值(可能是原始的)。

这是覆盖Http Headers并强制我的价值的代码。有没有更好/更合适的方法来做到这一点,以便我不会获得Accept-Language的两个条目?

https://gist.github.com/franz-see/66ce97850faa5faa22d5aa47b1ed797b

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.security.Permission;
import java.util.*;
import java.util.logging.Logger;

public class CustomHttpURLConnection extends HttpURLConnection {

    private static final Logger LOGGER = Logger.getLogger(CustomHttpURLConnection.class.getName());

    private final HttpURLConnection delegate;
    private final URL url;
    private Set<String> forcedHeaders = new LinkedHashSet<>();

    public CustomHttpURLConnection(HttpURLConnection delegate) {
        super(delegate.getURL());
        this.delegate = delegate;
        url = delegate.getURL();
    }

    @Override
    public String getHeaderFieldKey(int n) {
        String headerFieldKey = delegate.getHeaderFieldKey(n);
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderFieldKey(%d) = %s", url, n, headerFieldKey));
        return headerFieldKey;
    }

    @Override
    public String getHeaderField(int n) {
        String headerField = delegate.getHeaderField(n);
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderField(%d) = %s", url, n, headerField));
        return headerField;
    }

    @Override
    public void setRequestProperty(String key, String value) {
        if (!forcedHeaders.contains(key)) {
            delegate.setRequestProperty(key, value);
        }
    }

    @Override
    public long getHeaderFieldDate(String name, long Default) {
        long headerFieldDate = delegate.getHeaderFieldDate(name, Default);
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderFieldDate(%s, %d) = %s", url, name, Default, headerFieldDate));
        return headerFieldDate;
    }

    @Override
    public String getHeaderField(String name) {
        String headerField = delegate.getHeaderField(name);
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderField(%s) = %s", url, name, headerField));
        return headerField;
    }

    @Override
    public Map<String, List<String>> getHeaderFields() {
        Map<String, List<String>> headerFields = delegate.getHeaderFields();
        StringBuilder partialMessage = new StringBuilder();
        SortedSet<String> headerMessages = new TreeSet<>();
        if (headerFields != null) {
            for (Map.Entry<String, List<String>> headerField : headerFields.entrySet()) {
                String headerKey = headerField.getKey();
                String headerValue = StringUtils.join(headerField.getValue(), ",");
                headerMessages.add(String.format(" * %s = %s", headerKey, headerValue));
            }
            partialMessage.append(StringUtils.join(headerMessages, System.lineSeparator()));
        } else {
            partialMessage.append("<empty>");
        }
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderFields() = \n%s", url, partialMessage.toString()));
        return headerFields;
    }

    @Override
    public int getHeaderFieldInt(String name, int Default) {
        int headerFieldInt = delegate.getHeaderFieldInt(name, Default);
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderFieldInt(%s, %d) = %s", url, name, Default, headerFieldInt));
        return headerFieldInt;
    }

    @Override
    public long getHeaderFieldLong(String name, long Default) {
        long headerFieldLong = delegate.getHeaderFieldLong(name, Default);
        LOGGER.info(String.format("[%s] CustomHttpURLConnection#getHeaderFieldLong(%s, %d) = %s", url, name, Default, headerFieldLong));
        return headerFieldLong;
    }

    public void setForceRequestProperty(String key, String value) {
        delegate.setRequestProperty(key, value);
        forcedHeaders.add(key);
    }

    @Override
    public void setFixedLengthStreamingMode(int contentLength) {
        delegate.setFixedLengthStreamingMode(contentLength);
    }

    @Override
    public void setFixedLengthStreamingMode(long contentLength) {
        delegate.setFixedLengthStreamingMode(contentLength);
    }

    @Override
    public void setChunkedStreamingMode(int chunklen) {
        delegate.setChunkedStreamingMode(chunklen);
    }

    public static void setFollowRedirects(boolean set) {
        HttpURLConnection.setFollowRedirects(set);
    }

    public static boolean getFollowRedirects() {
        return HttpURLConnection.getFollowRedirects();
    }

    @Override
    public void setInstanceFollowRedirects(boolean followRedirects) {
        delegate.setInstanceFollowRedirects(followRedirects);
    }

    @Override
    public boolean getInstanceFollowRedirects() {
        return delegate.getInstanceFollowRedirects();
    }

    @Override
    public void setRequestMethod(String method) throws ProtocolException {
        delegate.setRequestMethod(method);
    }

    @Override
    public String getRequestMethod() {
        return delegate.getRequestMethod();
    }

    @Override
    public int getResponseCode() throws IOException {
        return delegate.getResponseCode();
    }

    @Override
    public String getResponseMessage() throws IOException {
        return delegate.getResponseMessage();
    }

    @Override
    public void disconnect() {
        delegate.disconnect();
    }

    @Override
    public boolean usingProxy() {
        return delegate.usingProxy();
    }

    @Override
    public Permission getPermission() throws IOException {
        return delegate.getPermission();
    }

    @Override
    public InputStream getErrorStream() {
        return delegate.getErrorStream();
    }

    public static FileNameMap getFileNameMap() {
        return URLConnection.getFileNameMap();
    }

    public static void setFileNameMap(FileNameMap map) {
        URLConnection.setFileNameMap(map);
    }

    @Override
    public void connect() throws IOException {
        delegate.connect();
    }

    @Override
    public void setConnectTimeout(int timeout) {
        delegate.setConnectTimeout(timeout);
    }

    @Override
    public int getConnectTimeout() {
        return delegate.getConnectTimeout();
    }

    @Override
    public void setReadTimeout(int timeout) {
        delegate.setReadTimeout(timeout);
    }

    @Override
    public int getReadTimeout() {
        return delegate.getReadTimeout();
    }

    @Override
    public URL getURL() {
        return delegate.getURL();
    }

    @Override
    public int getContentLength() {
        return delegate.getContentLength();
    }

    @Override
    public long getContentLengthLong() {
        return delegate.getContentLengthLong();
    }

    @Override
    public String getContentType() {
        return delegate.getContentType();
    }

    @Override
    public String getContentEncoding() {
        return delegate.getContentEncoding();
    }

    @Override
    public long getExpiration() {
        return delegate.getExpiration();
    }

    @Override
    public long getDate() {
        return delegate.getDate();
    }

    @Override
    public long getLastModified() {
        return delegate.getLastModified();
    }

    @Override
    public Object getContent() throws IOException {
        return delegate.getContent();
    }

    @Override
    public Object getContent(Class[] classes) throws IOException {
        return delegate.getContent(classes);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return delegate.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return delegate.getOutputStream();
    }

    @Override
    public String toString() {
        return delegate.toString();
    }

    @Override
    public void setDoInput(boolean doinput) {
        delegate.setDoInput(doinput);
    }

    @Override
    public boolean getDoInput() {
        return delegate.getDoInput();
    }

    @Override
    public void setDoOutput(boolean dooutput) {
        delegate.setDoOutput(dooutput);
    }

    @Override
    public boolean getDoOutput() {
        return delegate.getDoOutput();
    }

    @Override
    public void setAllowUserInteraction(boolean allowuserinteraction) {
        delegate.setAllowUserInteraction(allowuserinteraction);
    }

    @Override
    public boolean getAllowUserInteraction() {
        return delegate.getAllowUserInteraction();
    }

    public static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) {
        URLConnection.setDefaultAllowUserInteraction(defaultallowuserinteraction);
    }

    public static boolean getDefaultAllowUserInteraction() {
        return URLConnection.getDefaultAllowUserInteraction();
    }

    @Override
    public void setUseCaches(boolean usecaches) {
        delegate.setUseCaches(usecaches);
    }

    @Override
    public boolean getUseCaches() {
        return delegate.getUseCaches();
    }

    @Override
    public void setIfModifiedSince(long ifmodifiedsince) {
        delegate.setIfModifiedSince(ifmodifiedsince);
    }

    @Override
    public long getIfModifiedSince() {
        return delegate.getIfModifiedSince();
    }

    @Override
    public boolean getDefaultUseCaches() {
        return delegate.getDefaultUseCaches();
    }

    @Override
    public void setDefaultUseCaches(boolean defaultusecaches) {
        delegate.setDefaultUseCaches(defaultusecaches);
    }

    @Override
    public void addRequestProperty(String key, String value) {
        delegate.addRequestProperty(key, value);
    }

    @Override
    public String getRequestProperty(String key) {
        return delegate.getRequestProperty(key);
    }

    @Override
    public Map<String, List<String>> getRequestProperties() {
        return delegate.getRequestProperties();
    }

    @Deprecated
    public static void setDefaultRequestProperty(String key, String value) {
        URLConnection.setDefaultRequestProperty(key, value);
    }

    @Deprecated
    public static String getDefaultRequestProperty(String key) {
        return URLConnection.getDefaultRequestProperty(key);
    }

    public static void setContentHandlerFactory(ContentHandlerFactory fac) {
        URLConnection.setContentHandlerFactory(fac);
    }

    public static String guessContentTypeFromName(String fname) {
        return URLConnection.guessContentTypeFromName(fname);
    }

    public static String guessContentTypeFromStream(InputStream is) throws IOException {
        return URLConnection.guessContentTypeFromStream(is);
    }

}

注意:Javafx WebView正在使用HttpUrlConnection。

0 个答案:

没有答案