V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
liuyanjun0826
V2EX  ›  Android

private static final HttpURLConnection setupConnection 是 import 的还是自建的?

  •  
  •   liuyanjun0826 · 2018-12-01 12:28:01 +08:00 · 7861 次点击
    这是一个创建于 2188 天前的主题,其中的信息可能已经有所发展或是发生改变。
    private static final HttpURLConnection setupConnection(URL url, boolean imposeUseragent, boolean followHttpHttpsRedirects, int cycle) throws IOException, NoSuchAlgorithmException, KeyManagementException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setDoInput(true);
    connection.setDoOutput(false);
    if (imposeUseragent) {
    connection.setRequestProperty(KEY_USERAGENT, VALUE_USERAGENT); // some feeds need this to work properly
    }
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.setUseCaches(false);

    if (url.getUserInfo() != null) {
    connection.setRequestProperty("Authorization", "Basic "+BASE64.encode(url.getUserInfo().getBytes()));
    }
    connection.setRequestProperty("connection", "close"); // Workaround for android issue 7786
    connection.connect();

    String location = connection.getHeaderField("Location");

    if (location != null && (url.getProtocol().equals(Strings._HTTP) && location.startsWith(Strings.HTTPS) || url.getProtocol().equals(Strings._HTTPS) && location.startsWith(Strings.HTTP))) {
    // if location != null, the system-automatic redirect has failed which indicates a protocol change
    if (followHttpHttpsRedirects) {
    connection.disconnect();

    if (cycle < 5) {
    return setupConnection(new URL(location), imposeUseragent, followHttpHttpsRedirects, cycle+1);
    } else {
    throw new IOException("Too many redirects.");
    }
    } else {
    throw new IOException("https<->http redirect - enable in settings");
    }
    }
    1 条回复    2019-03-26 14:51:39 +08:00
    43486250
        1
    43486250  
       2019-03-26 14:51:39 +08:00
    Android 6.0 版本已移除对 Apache HTTP 客户端的支持
    如果您的应用使用该客户端,并以 Android 2.3 ( API 级别为 9 )或更高版本为目标平台,请改用 HttpURLConnection 类。此 API 效率更高,能够通过透明压缩和响应缓存减少网络使用,并可最大限度降低耗电量。要继续使用 Apache HTTP API,须先在 build.gradle 文件中声明以下编译时依赖项:

    android {

    useLibrary 'org.apache.http.legacy'

    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5485 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 07:38 · PVG 15:38 · LAX 23:38 · JFK 02:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.