【Spring】官网教程阅读笔记(六):访问Twitter

来源:互联网 发布:清华大学 人工智能 编辑:程序博客网 时间:2024/05/17 07:45

【前言】这一节要建立一个web应用,从Twitter上扒数据,因为强大的技术原因,这个教程定位在示范,本人正在尝试访问weixin API,如若成功会及时分享。原文链接

【实现目标】你将在这里从Twitter上获取登录用户信息并且扒出该用户关注的人。

【准备工作】pom.xml

    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-thymeleaf</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.social</groupId>            <artifactId>spring-social-twitter</artifactId>        </dependency>    </dependencies>
看着配置文件,Twitter有专用的模块。其他专有模块有Facebook、linkedIn、GitHub、Triplt。很遗憾没有weibo wexin什么的,不过social模块倒是有一些公共的方案:参考链接

有时间的话会研究一下social模块


激活Twitter

在我们从Twitter上抓取数据之前,先得在Twitter上申请一个个人ID和密码,然后在spring.social.twitter.appId和spring.social.twitter.appSecret属性上设置好账户。可以用任何Spring Boot支持的方式为应用设置这些值,比如properties文件的方式:

src/main/resources/application.properties


spring.social.twitter.appId={{put app ID here}}spring.social.twitter.appSecret={{put app secret here}}

这个properties文件里两个属性都是假的值,在使用的时候需要自己填入一个有效账号、密码。为了让示例代码能跑起来,去注册用户吧,然后在这里填上对应的属性(苦了天朝用户啊)。

配置文件和Spring Social Twitter 模块会自动触发配置Spring Social ConnectController,TwitterConnectionFactory和Spring Social连接框架的其他部分。(也就是说,如果你要连weibo,这一大串都要自己配置)

创建连接视图

虽然ConnectController大部分需要面对Twitter重定向,并且处理Twitter的重定向,同事它还展示GET请求的连接状态(请求/连接)。当没有连接存在时,ConnectController引用一个命名为connect/{provider ID}Connect的视图;当有连接时引用名为connect/{provider ID}Connected的视图。这里{provider ID}为"Twitter".

ConnectController并不定义连接视图,你需要自己创建这些视图。首先这有一个Thymeleaf视图,他在没有Twitter连接时出现:(View就是一个web页)

src/main/resources/templates/connect/twitterConnect.html


<html><head><title>Hello Twitter</title></head><body><h3>Connect to Twitter</h3><form action="/connect/twitter" method="POST"><div class="formInfo"><p>You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.</p></div><p><button type="submit">Connect to Twitter</button></p></form></body></html>

这张Form表单将Post到 由ConnectController处理的/connect/twitter上,并会剔除认证流程的代码。

而当有连接的时候,将采用这样的视图:

src/main/resources/templates/connect/twitterConnected.html

<html><head><title>Hello Twitter</title></head><body><h3>Connected to Twitter</h3><p>You are now connected to your Twitter account.Click <a href="/">here</a> to see your Twitter friends.</p></body></html>

获取Twitter数据

在应用中配置好Twitter之后,现在可以写MVC控制器了。我们用这个控制器从已经在浏览器上登录的验证用户上捕获数据。HelloController(Controller的名字)是这样样子滴:

package hello;import javax.inject.Inject;import org.springframework.social.connect.ConnectionRepository;import org.springframework.social.twitter.api.CursoredList;import org.springframework.social.twitter.api.Twitter;import org.springframework.social.twitter.api.TwitterProfile;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping("/")public class HelloController {    private Twitter twitter;    private ConnectionRepository connectionRepository;    @Inject    public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {        this.twitter = twitter;        this.connectionRepository = connectionRepository;    }    @RequestMapping(method=RequestMethod.GET)    public String helloTwitter(Model model) {        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {            return "redirect:/connect/twitter";        }        model.addAttribute(twitter.userOperations().getUserProfile());        CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();        model.addAttribute("friends", friends);        return "hello";    }}

这里我们靠依赖注入的Twitter对象传入HelloController的构造器来生成HelloController对象。Twitter对象是一个指向Spring Social的Twitter API绑定的引用。(Spring Social Twitter binding 说明)
helloTwitter()用@RequestMapping注解标记,表明它是处理\路径GET请求的方法。它先检查应用是否能通过鉴权访问用户数据。如果不能,用户将被重定向到ConnectController上开始鉴权过程。
如果应用鉴权通过了,它就可以获取大部分用户信息和某个Twitter用户关注的人的信息列表(而不是关注他的人的信息)。这些信息都被放入视图定义的"hello"模块中。

讲到"hello"视图,下面贴出以Thymeleaf模板出现的hello视图:

src/main/resources/templates/hello.html

<html><head><title>Hello Twitter</title></head><body><h3>Hello, <span th:text="${twitterProfile.name}">Some User</span>!</h3><h4>These are your friends:</h4><ul><li th:each="friend:${friends}" th:text="${friend.name}">Friend</li></ul></body></html>

这个模板简单展示了向用户问候,和用户朋友的列表。注意,即便是获取了用户全部特性,在这个模板中只用到了用户名。

让应用可运行

Application就是最普通的@SpringBootApplication类型,一个SpringApplication.run();搞定。

package hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

Build和运行

Build过程一样。

运行的时候,需要这样操作:首先把应用跑起来,然后在本机浏览器上访问http://localhost:8080. 由于现在还没有建立到Twitter的连接,我们将会看到一个提示连接到Twitter的页面。

当你点击Connect to Twitter按钮的时候,浏览器将重定向到Twitter鉴权


此时,Twitter会询问是否允许样例应用读取你的推文查看你的关注人。这里,屏幕上的显示有些误导,因为此时的应用只会读取你的信息已经你关注人的信息。点击Authorize app获取上述访问权限。

一旦获取了权限,Twitter重定向浏览器到应用。此时连接建立,该连接保存在连接仓库中。此时应该可以看见页面重定向完成,连接成功。


再点here就能看的登录用户的名字,已经该用户关注的人了。


【小结】
本文小结不知道从何说起,Spring Social模块需要再开发才能适配国内的情况。
    Spring Social ConnectController要自己配置好参数,创建一个类似TwitterConnectionFactory的WeiboConnectioinFactory,Twitter对象。HelloController.java中的Model为org.springframework.ui.Model接口,可以把他当做是Map。该接口对象如何注入,由Spring完成。helloTwitter方法返回一个"Hello"这点很莫名其妙,不过从几个地方可以初步猜测出这个hello对应着view的名字。
    hello这个view里面,twitterProfile对象,friends对象都定义在helloTwitter()方法中,twitterProfile对应model.addAttribute(twitter.userOperations().getUserProfile());friends对应model.addAttribute("friends", friends);



0 0
原创粉丝点击