2015-07-21 118 views
2

我有一个占位符站点的压缩网址(http://placehold.it/600/24f355)。 如何从Android中的压缩网址获取完整网址(https://placeholdit.imgix.net/~text?txtsize=56&bg=24f355&txt=600%C3%97600&w=600&h=600)?如何从Android中的压缩网址获得完整的URL?

我尝试了以下,但我得到相同的网址,我给。

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

相同的代码为我工作。尝试使用HttpURLConnection代替URLConnection。 – gRaWEty

+0

@gRaWEty - OP的代码也不适用于我。我再次获得相同的“URL”。 – TDG

+0

您需要遵循重定向,直到您获得3xx响应代码。所以你可以递归调用相同的方法,直到你得到200,201,202 –

回答

3

this article描述,您需要检查响应代码(conn.getResponseCode()),如果它是一个3XX(=重定向),就可以从“位置”报头字段来获得新的URL。

String newUrl = conn.getHeaderField("Location"); 
+0

谢谢,它的工作原理 –

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); 
} 
相关问题