Jsoup没有连接到Android Studio的网页



我现在正在做一个项目,我在一个类中使用jsoup函数retrieveMedia,以便返回一个充满网页数据的数组列表。我在一个线程中运行它,因为你不应该从主线程连接到url。我运行它并加入它。然而,它不起作用(我在Eclipse中测试了与Android Studio分开的相同代码,它工作得很好)。似乎无论我怎么做,我都不能让jsoup连接到网页。下面是我的类mediaretriver。

public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}

Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

return mediaOutput;
}
}

从另一个类运行这个类的方法,它永远不会连接。什么好主意吗?

既然你说这个问题只在Android中存在,看起来你应该将用户代理字符串添加到你的请求中-首先获得正确显示站点的浏览器的用户代理字符串,然后将其添加到请求中:

doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();

作为旁注-如果你正在捕获异常,不要打印自己的错误消息-打印原始消息,这可能非常有用。

相关内容

最新更新