如何将ThreadLocal用于HttpUrlConnection / HttpsUrlConnection

时间:2016-04-05 09:17:15

标签: java android httpurlconnection

我有org.apache用于我的应用程序中的网络的类。由于现在已弃用,我想使用HttpUrlConnection而不使用第三方库。我面临的主要挑战是ThreadLocal。我有一个使用DefaultHttpClient的restclient,并希望用HttpUrlConnection替换它,如下面的代码所示

require 'win32ole'

wsh = WIN32OLE.new("WScript.Shell")
wsh.Run("Notepad.exe")
while not wsh.AppActivate("Notepad")
  sleep 1
end

def fileToArray(file)
    x = []
    File.foreach("#{file}") do |line|
        x << line.split('')
    end
    return x.flatten!
end

tests = fileToArray("readfrom.txt")

x = 0
while x <= tests.length
    send = tests[x]
    wsh.SendKeys("#{send}")
    x += 1
    sleep 0.1
end

如果我尝试用HttpUrlConnection替换DefaultHttpClient,我如何在这里获取Url以打开连接?

我见过与ThreadLocal相关的各种帖子,但我无法理解如何传递url并返回客户端实例。

为了澄清更多我想做这样的事情......

public static class UniqueHttpClient {

    private static ThreadLocal<DefaultHttpClient> uniquelocal =

    new ThreadLocal<DefaultHttpClient>() {

        @Override
        protected DefaultHttpClient initialValue() {

            BasicHttpParams httpParameters = new BasicHttpParams();

            HttpConnectionParams
                    .setConnectionTimeout(httpParameters, 90000);

            HttpConnectionParams.setSoTimeout(httpParameters, 90000);

            DefaultHttpClient client;
            // registers schemes for both http and httpsb

            SchemeRegistry registry = new SchemeRegistry();

            registry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));

            KeyStore trustStore;

            SSLSocketFactory sslSocketFactory;

            try {

                trustStore = KeyStore
                        .getInstance(KeyStore.getDefaultType());

                trustStore.load(null, null);

                sslSocketFactory = new MySSLSocketFactory(trustStore);

            } catch (Exception exEXCP) {

                exEXCP.printStackTrace();

                sslSocketFactory = SSLSocketFactory.getSocketFactory();
            }

            sslSocketFactory
                    .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            registry.register(new Scheme("https", sslSocketFactory, 443));

            ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(
                    httpParameters, registry);

            client = new DefaultHttpClient(manager, httpParameters);

            return client;
        }

    };

    public static DefaultHttpClient getUniqueHttpClient() {

        return uniquelocal.get();
    }

} // class UniqueHttpClient

在上面的代码中我如何从多个客户端获取url(requestUrl),以便我能够成功打开openConnection并返回urlConn对象。 提前谢谢!

0 个答案:

没有答案