V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
liuyanjun0826
V2EX  ›  Android

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

  •  
  •   liuyanjun0826 · Dec 1, 2018 · 12045 views
    This topic created in 2718 days ago, the information mentioned may be changed or developed.
    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 replies    2019-03-26 14:51:39 +08:00
    43486250
        1
    43486250  
       Mar 26, 2019
    Android 6.0 版本已移除对 Apache HTTP 客户端的支持
    如果您的应用使用该客户端,并以 Android 2.3 ( API 级别为 9 )或更高版本为目标平台,请改用 HttpURLConnection 类。此 API 效率更高,能够通过透明压缩和响应缓存减少网络使用,并可最大限度降低耗电量。要继续使用 Apache HTTP API,须先在 build.gradle 文件中声明以下编译时依赖项:

    android {

    useLibrary 'org.apache.http.legacy'

    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1709 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 16:24 · PVG 00:24 · LAX 09:24 · JFK 12:24
    ♥ Do have faith in what you're doing.