我得到了一个缩短的 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 中定义的。