2015-07-21 63 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); 
} 
相關問題