我在使用JSoup连接到网址时遇到了问题.
我试图测试的网址是www.xbox.com/en-US/security,这是302(我认为)重定向到 http://www.xbox.com/en-US/Live/Account-Security.我已经设置了jsoup来跟随重定向并使用.headers("location")获取新的url.返回的网址是/ en-US/Live/Account-Security.我不知道如何处理它,我的代码如下:
while (i < retries){
try {
response = Jsoup.connect(checkUrl)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.followRedirects(false)
.timeout(10000)
.execute();
success = true;
break;
} catch (SocketTimeoutException ex){
timeout = true;
} catch (MalformedURLException ep){
malformedUrl = true;
}catch (IOException e) {
statusCode = 404;
}
}
private void getStatus(){
if (success){
statusCode = response.statusCode();
success = false;
}
if (statusCode >= 300 && statusCode <= 399){
//System.out.println("redirect: " +statusCode + " " +checkUrl);
checkUrl = response.header("location");
//System.out.println(checkUrl);
connect();
getStatus();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人有关于如何处理这个问题的建议?或者我应该检查一下checkUrl = response.header("location"); 看它是否是一个有效的网址,如果不是不测试它?
首先要做的事情是:如果您尝试访问"www.xbox.com/en-US/security",它会抛出MalformedException,因此不会将您重定向到您想要的位置.
比起我只使用布尔变量成功的问题,如果捕获到任何异常,则将其设置为false.然后我再也不知道你是否正在使用超时或畸形变量.
之后我会说IOException之后的行永远不会有用.我再说不出来,因为我看不到完整的代码.
现在......对于您的问题:返回的字符串是您提供的第一个URL中的域.它会像这样:
//Assuming you won't ever change it, make it a final
//variable for less memory usage.
final String URL = "http://www.xbox.com/en-US/security";
//Whatever piece of processing here
//Some tests just to make sure you'll get what you're
//fetching:
String newUrl = ""
if (checkUrl.startsWith("/"))
newUrl = URL + checkUrl;
if (checkUrl.startsWith("http://"))
newUrl = checkUrl;
if (checkUrl.startsWith("www"))
newUrl = "http://" + checkUrl;
Run Code Online (Sandbox Code Playgroud)
这段代码基本上可以确保您可以浏览网址,而不会获得一些MalformedUrlException.我建议在某处放置一个manageUrl()方法并测试所提取的URL是否在您正在搜索的域内,或者您最终可能会在e-commerces或publicuty网站中.
希望它有帮助=)