6

我正在尝试采用缩短的 url 并将其扩展为 java 中字符串格式的原始全长 url。我已经能够在网上找到一个教程,但是我无法得到这个来真正让我得到完整的网址。有没有人这样做过或知道如何做到这一点?任何帮助都是巨大的,谢谢

URLConnection conn = null;
try {
    URL inputURL = new URL("http://bit.ly/9mglq8");
    conn = inputURL.openConnection();

} catch (MalformedURLException e) {

} catch (IOException ioe) {

}
String realU = conn.toString();
Toast.makeText(ImagetestActivity.this, realU,
               Toast.LENGTH_LONG).show();
4

4 回答 4

7
System.out.println("Short URL: "+ shortURL);
                urlConn =  connectURL(shortURL);
                urlConn.getHeaderFields();
                System.out.println("Original URL: "+ urlConn.getURL());

/* connectURL - This function will take a valid url and return a 
URL object representing the url address. */
URLConnection connectURL(String strURL) {
        URLConnection conn =null;
 try {
     URL inputURL = new URL(strURL);
     conn = inputURL.openConnection();
            int test = 0;

 }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;
}
于 2012-05-19T00:40:01.177 回答
3

您可能想要使用官方 bit.ly API 中的扩展查找,或 URLConnection 的getHeaderField方法来获取Location标题。

我从来没有做过这些,我假设后者不会有任何问题,但我想官方方法可能是保证你得到你需要的东西的方法。

于 2012-05-19T00:38:53.050 回答
1
public static void getURL(String bitly) throws SQLException {   
        
        URLConnection conn = null;
        String bitlyLink = null;
        try {
            URL inputURL = new URL(bitlyLink);
            conn = inputURL.openConnection();
            conn.getHeaderFields();
            System.out.println("Original URL: "+ conn.getURL());

        } catch(Exception e) { 
          System.out.println("Error: "+ e.getMessage());
        }
}
于 2020-07-11T14:09:58.167 回答
0

从 bit.ly 规范:

比特利是如何工作的?bitly 通过发出“301 重定向”来工作:一种使网页在许多 URL 下可用的技术。当您使用 bitly 缩短链接时,您会将点击从 bitly 重定向到目标 URL。301 重定向是最有效且对搜索引擎友好的网页重定向方法,也是 bitly 使用的方法。由于 bitly 不会重复使用或修改链接,我们认为我们的重定向是永久性的。

这意味着当您收到 301 响应代码时,您必须查看“位置”标头以确定重定向到的位置。这是一个示例 301 响应:

HTTP/1.1 301 永久移动位置:http ://www.example.org/index.asp

于 2012-05-19T05:45:43.123 回答