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

2018-12-01 12:28:01 +08:00
 liuyanjun0826
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");
}
}
7770 次点击
所在节点    Android
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'

}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/513297

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX