无法从给定的缩短的 URL 中获取扩展的 URL
Can't fetch expanded URL from a given shortened URL
我得到了一个缩短的 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 是在 class
ExpandUrl.
中定义的
好吧,代码在 Eclipse 中有效,但在 android 中无效。原因是您在主线程中执行此操作并阻止了它。 Android 不允许您这样做并抛出运行时错误。
我已尝试在 android 中使用 AsyncTask
实现您的代码。它工作正常。
试一试。
要了解有关 AsyncTask
的更多信息,请关注:Android Documentation on AsyncTask
祝你好运!
我得到了一个缩短的 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 是在 class
ExpandUrl.
好吧,代码在 Eclipse 中有效,但在 android 中无效。原因是您在主线程中执行此操作并阻止了它。 Android 不允许您这样做并抛出运行时错误。
我已尝试在 android 中使用 AsyncTask
实现您的代码。它工作正常。
试一试。
要了解有关 AsyncTask
的更多信息,请关注:Android Documentation on AsyncTask
祝你好运!