在Java中将缩短的URL扩展为其原始的完整长度URL

时间:2012-05-19 00:28:46

标签: java url urlconnection

我正在尝试使用缩短的网址并将其扩展为原始的全长网址,以java格式的字符串格式显示。我已经能够在线追踪一个教程,但是我无法让它真正得到我的完整网址。有没有人以前做过这个或者知道怎么做?任何帮助都很大,谢谢

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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:3)

您可能希望使用官方bit.ly API中的expand lookup或URLConnection的getHeaderField方法来获取Location标头。

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

答案 2 :(得分: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());

        }
}

答案 3 :(得分:0)

来自bit.ly规范:

怎么有点工作? 通过发布“301重定向”来进行有点工作:一种在许多URL下提供网页的技术。当您使用bitly缩短链接时,您会将点击从bitly重定向到目标URL。 301重定向是用于网页重定向的最有效且搜索引擎友好的方法,并且是有点使用的。因为有点不会重复使用或修改链接,我们认为我们的重定向是永久性的。

这意味着您必须查看“位置”标题,以确定在获得301响应代码时重定向到哪里。以下是301回复示例:

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