【发布时间】:2018-05-12 06:00:02
【问题描述】:
我得到了一个缩短的 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中定义的。
【问题讨论】:
-
你得到了哪个 runtimeException? Android 也有一个 getHeaderField 方法,它接受一个字符串。 developer.android.com/reference/java/net/…
-
感谢您的指点。
-
能否请您粘贴使用上述方法的代码?
-
@speedious 检查此链接:- stackoverflow.com/questions/18201984/…
-
正如我所提到的,代码在 Eclipse 中运行良好。它获取所需的 url,但为什么在 android 中同样不起作用?我错过了什么?
标签: java android httpurlconnection