java - 解析 Facebook 的 XML 查询响应问题

标签 java xml facebook facebook-fql jdom

嘿伙计们! :) 我正在开发一项服务,可以从 Facebook API 捕获点赞数、分享数等。 但是有一个问题,因为我从 fqlResponse.getChild() 得到一个空指针异常。

我认为自动检测xmls doctype有问题,所以我手动定义了doctype,但问题仍然存在。也许 facebooks xml 文档类型不正确? 捕获方法如下:

public void refreshLikesSharesClicksAndTotal() throws JDOMException, IOException {
    URL fqlURL = new URL("https://api.facebook.com/method/fql.query?query=select  like_count,    total_count, share_count, click_count from link_stat where url=\"" + this.url.toString() + "\"");
    Document inputXML = new SAXBuilder().build(fqlURL);
    DocType docType = new DocType("xml", "http://www.w3.org/2001/XMLSchema-instance");
    inputXML.setDocType(docType);
    Element fqlResponse = inputXML.getRootElement().getChild("link_stat");
    Element likes = fqlResponse.getChild("like_count");
    logger.info("Likes: " + likes.getText());
    Element shares = fqlResponse.getChild("share_count");
    Element clicks = fqlResponse.getChild("click_count");
    Element total = fqlResponse.getChild("total_count");

    this.likes = Integer.parseInt(likes.getText());
    this.shares = Integer.parseInt(shares.getText());
    this.clicks = Integer.parseInt(clicks.getText());
    this.total = Integer.parseInt(total.getText());

}

XML 示例: https://api.facebook.com/method/fql.query?query=select%20%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20where%20url=%22http://heise.de%22

德语问题描述: http://www.java-forum.org/xml-co/118648-problem-beim-parsen-facebook-xml.html

感谢您的帮助! 白色内克斯

最佳答案

你可以这样做:-

    URL url = new URL("https://api.facebook.com/method/fql.query?query=select%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20where%20url=%22http://heise.de%22");

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());
    XPath xPath = XPathFactory.newInstance().newXPath();

    int likeCount = Integer.parseInt(xPath.evaluate("//like_count/text()", doc));
    int totalCount = Integer.parseInt(xPath.evaluate("//total_count/text()", doc));
    int shareCount = Integer.parseInt(xPath.evaluate("//share_count/text()", doc));
    int clickCount = Integer.parseInt(xPath.evaluate("//click_count/text()", doc));

确保使用 %20 和 %22 对 URL 中的空格和双引号进行适当编码。我已经测试过这段代码,它对我有用。

关于java - 解析 Facebook 的 XML 查询响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097789/

相关文章:

java - 在不打开日历的情况下添加日历事件

java - @XToX 带注释的字段的主要术语(最好是一个词)是什么?

java - 当其中一个 float 结果为 NaN 时,我可以让 Java 在 float 之间进行比较时抛出异常吗?

html - <br 风格 ="page-break-after: always"> 不工作 Windows 8/8.1

facebook - 应用程序配置不允许给定 URL

java - SQLite 中的 android errno

regex - 使用 Notepad++ 中的正则表达式在xml标签中的字符串中查找特定单词?

c# - .NET 中是否有 XmlDocument.LoadXml() 的 Java 等效项?

android - 如何在 android 中使用 facebook sdk 在墙上的帖子中标记 friend ?

ios - 尽管有正确的许可,但没有收到 facebook 用户的电子邮件