Can't fetch expanded URL from a given shortened URL

末鹿安然 提交于 2021-02-18 08:48:41

问题


I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.

public String expand(String shortenedUrl){
        URL url = null;
        try {
            url = new URL(shortenedUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        // open connection
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // stop following browser redirect
        httpURLConnection.setInstanceFollowRedirects(false);
        // extract location header containing the actual destination URL
        String expandedURL = httpURLConnection.getHeaderField("Location");
        httpURLConnection.disconnect();


        return expandedURL;
    }

The code works fine in Eclipse but the same doesn't work in android.

String expandedURL = httpURLConnection.getHeaderField("Location");

The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.

int status = 0;
    try {
        status = httpURLConnection.getResponseCode();
    } catch (IOException e) {
        e.printStackTrace();
    }

This piece of code also has the same problem. works in eclipse but not in android.

Any kind of help will be greatly appreciated.

Edit: The code using above function is,

ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);

Note: The function expand is defined inside the class ExpandUrl.


回答1:


Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.

I have tried to implement your code using AsyncTask in android. It works fine. Give it a try.

To know more about AsyncTask follow: Android Documentation on AsyncTask

Good Luck!



来源:https://stackoverflow.com/questions/50303327/cant-fetch-expanded-url-from-a-given-shortened-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!