Java 如何在Android中从压缩URL获取完整URL?

Java 如何在Android中从压缩URL获取完整URL?,java,android,Java,Android,我有一个PlaceHolder站点()的压缩URL。 如何在Android中从压缩的URL获取完整的URL() 我尝试了以下方法,但得到的URL与我给出的相同 public static void main(String[] args) { String shortURL = "http://placehold.it/600/24f355"; System.out.println("Short URL: " + shortURL); URLConnection urlConn = connec

我有一个PlaceHolder站点()的压缩URL。 如何在Android中从压缩的URL获取完整的URL()

我尝试了以下方法,但得到的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;
}
如中所述,您需要检查响应代码(
conn.getResponseCode()
),如果是3xx(=重定向),则可以从“位置”标题字段获取新URL

String newUrl = conn.getHeaderField("Location");
试试这个:

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);
}

同样的代码也适用于我。尝试用HttpURLConnection代替URLConnection。@gRaWEty-OP的代码对我也不起作用。我再次收到相同的
URL
。您需要按照重定向操作,直到收到3xx响应代码。所以你可以递归调用相同的方法,直到你得到200201202Check我的答案。这对我很有用@TDG@gRaWEty-你回答的密码对我有用。