问题描述
我给了我一个缩短的网址,我想得到扩展的表格.下面的java函数用于实现此目的.
I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
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中则无法正常工作.
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
上面的行抛出 java.lang.RuntimeException:无法启动活动ComponentInfo
.错误指向上面的行.如果删除上面的行,则不会遇到错误.即使我不能使用 getResponseCode()
函数.
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo
. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode()
function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
这段代码也有同样的问题.在Eclipse中有效,但在android中无效.
This piece of code also has the same problem. works in eclipse but not in android.
任何帮助将不胜感激.
编辑:使用上述功能的代码是
The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
注意:函数expand是在 class
ExpandUrl内部定义的.
Note: The function expand is defined inside the class
ExpandUrl.
推荐答案
好吧,该代码在Eclipse中有效,但在android中不起作用.原因是您正在主线程中执行该操作并阻止了它.Android不允许您这样做并引发运行时错误.
Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
我尝试使用android中的 AsyncTask
来实现您的代码.它工作正常.试试看.
I have tried to implement your code using AsyncTask
in android. It works fine.Give it a try.
要了解有关 AsyncTask
的更多信息,请遵循: Android文档位于AsyncTask
To know more about AsyncTask
follow: Android Documentation on AsyncTask
祝你好运!
这篇关于无法从给定的简短网址中获取展开的网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!