我有占位符网站的压缩网址(http://placehold.it/600/24f355)。 如何从Android中的压缩网址获取完整的网址(https://placeholdit.imgix.net/~text?txtsize=56&bg=24f355&txt=600%C3%97600&w=600&h=600)?
我尝试了以下内容,但我得到了相同的网址。
public static void main(String[] args) {
String shortURL = "http://placehold.it/600/24f355";
System.out.println("Short URL: " + shortURL);
URLConnection urlConn = connectURL(shortURL);
urlConn.getHeaderFields();
System.out.println("Original URL: " + urlConn.getURL());
}
static URLConnection connectURL(String strURL) {
URLConnection conn = null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
} catch (MalformedURLException e) {
System.out.println("Please input a valid URL");
} catch (IOException ioe) {
System.out.println("Can not connect to the URL");
}
return conn;
}
答案 0 :(得分:3)
如this article中所述,您需要检查响应代码(conn.getResponseCode()
),如果它是3xx(=重定向),您可以从"中获取新的URL。位置和#34;标题字段。
String newUrl = conn.getHeaderField("Location");
答案 1 :(得分:1)
试试这个:
public static void main(String[] args) throws IOException {
URL address=new URL("your short URL");
//Connect & check for the location field
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) address.openConnection(Proxy.NO_PROXY);
connection.setInstanceFollowRedirects(false);
connection.connect();
String expandedURL = connection.getHeaderField("Location");
if(expandedURL != null) {
URL expanded = new URL(expandedURL);
address= expanded;
}
} catch (Throwable e) {
System.out.println("Problem while expanding {}"+ address+ e);
} finally {
if(connection != null) {
System.out.println(connection.getInputStream());
}
}
System.out.println("Original URL"+address);
}