我收到一个缩短的网址,我希望得到扩展后的表单。下面的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);
注意:函数展开是在class
ExpandUrl。
答案 0 :(得分:0)
嗯,代码在Eclipse中工作但在android中不起作用。原因是你在主线程中执行它并阻止它。 Android不允许你这样做并抛出运行时错误。
我尝试在android中使用AsyncTask
实现您的代码。它工作正常。
试一试。
要详细了解AsyncTask
关注:Android Documentation on AsyncTask
祝你好运!