我正在尝试获取用户输入的 url 的图标,例如
_url = "google.com";
我使用 HttpUrlConnection 从主机 url 的 /favicon.ico
扩展中获取图标的位图。
String faviconString = Uri.parse(_url).getHost() + "/favicon.ico";
URL faviconUrl = null;
Bitmap favicon = null;
try
{
faviconString = "http://" + faviconString;
faviconUrl = new URL(faviconString);
HttpURLConnection connection = (HttpURLConnection) faviconUrl.openConnection();
connection.setDoInput(true);
connection.connect();
favicon = BitmapFactory.decodeStream(connection.getInputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
return favicon;
但是,由于用户可能不会指定 http://
或 https://
,因此我必须自己添加。我遇到的问题是,如果我在 url 前面添加 http://
,一切都会正常,但是对于 https://
,一些网站会返回图标,其他人只会给我 null。我如何找出哪个页面使用 https
?我应该为每种情况添加 http://
吗?是否有任何网站严格限制为 https
并会在使用 http
时返回 null?
最佳答案
除非你使用 user2558882 的 idea或者有一些其他工具可以为您获取网站图标,您将不得不检查 http 和 https url。没有其他方法可以做到这一点。这是使用网络困难的一部分。
也许以不同的方式看待您的代码并将您尝试做的事情分解成更小、更易于管理的部分会更好一些?
public void getFavicon(String host) {
URL httpUrl = this.getHttpUrl(host + "/favicon.ico");
Bitmap favicon = this.getBitmap(httpUrl);
if (favicon == null) {
URL httpsUrl = this.getHttpsUrl(host + "/favicon.ico");
favicon = this.getBitmap(httpsUrl);
}
if (favicon == null) {
throw new FaviconMissingException("Unable to find favicon for host: " + host);
}
return favicon;
}
public URL getHttpUrl(String uri) throws MalformedURLException {
// There are better ways of building a url then string concationation.
return new URL("http://" + uri);
}
public URL getHttpsUrl(String uri) throws MalformedURLException {
// There are better ways of building a url then string concationation.
return new URL("https://" + uri);
}
public Bitmap getBitmap(URL url) {
InputStream inputStream = getInputStream(url);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap
}
public InputStream getInputStream(URL url) {
// Please use a real connection library like HTTPClient here!
// HttpClient will handle timeouts, redirects, and things like that for you.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
return connection.getInputStream();
}
顺便说一句,关注一个或两个连接比编写发出两个请求的代码要花费更多的时间。我几乎可以保证谷歌会根据需要发出两个请求。如果它对谷歌来说足够好,那么对我来说也足够好。
最后,如果您开始发现发出两个请求确实花费了太多时间,那么请采取一些措施来提高性能。
关于java - HttpURLConnection - "https://"与 "http://",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18918662/