0

我得到了一个缩短的 url,我想得到扩展的表单。下面的java函数用于实现这一点。

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

该代码在 Eclipse 中运行良好,但在 android 中却无法运行。

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

上面的行抛出java.lang.RuntimeException: Unable to start activity ComponentInfo. 并且错误指向上面的行。如果我删除上述行,则不会遇到错误。即使我无法使用getResponseCode()功能。

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

这段代码也有同样的问题。适用于eclipse但不适用于android。

任何形式的帮助将不胜感激。

编辑:使用上述功能的代码是,

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

注意:函数 expand 是在classExpandUrl 中定义的。

4

1 回答 1

0

好吧,代码在 Eclipse 中有效,但在 android 中无效。原因是您在主线程中执行此操作并阻止它。Android 不允许您这样做并引发运行时错误。

我试图AsyncTask在 android 中使用你的代码来实现。它工作正常。试试看。

要了解更多信息,请AsyncTask关注:关于 AsyncTask 的 Android 文档

祝你好运!

于 2018-05-13T04:13:53.123 回答