1

如何使用 spring social Twitter API 获取原始 JSON 数据推文?有“Tweet”类,但我没有找到任何允许检索原始推文内容的函数 - 由 Twitter 以 JSON 格式返回。

4

1 回答 1

1

我不知道您为什么想要原始 JSON 数据,但这是可能的,您可以通过以下方式获取它:

按照本指南设置 Spring Social Twitter。

如果您想要来自 Twitter 的原始 JSON 数据,那么您可以使用RestTemplateTwitterTemplate.

在上述指南中添加此控制器:

@Controller
@RequestMapping("/jsontweets")
public class JsonTweetsController {

    private ConnectionRepository connectionRepository;

    private TwitterTemplate twitterTemplate;

    @Inject
    public JsonTweetsController(Twitter twitter, ConnectionRepository connectionRepository, TwitterTemplate twitterTemplate) {
        this.connectionRepository = connectionRepository;
        this.twitterTemplate = twitterTemplate;
    }

    @RequestMapping(method=RequestMethod.GET)
    public String helloTwitter(@RequestParam String search, Model model) {
        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            return "redirect:/connect/twitter";
        }

        Connection<Twitter> con = connectionRepository.findPrimaryConnection(Twitter.class);
        UserProfile userProfile = con.fetchUserProfile();
        String username =  userProfile.getFirstName() + " " + userProfile.getLastName(); 

        RestTemplate restTemplate = twitterTemplate.getRestTemplate();

        //More Query Options @ https://dev.twitter.com/rest/reference/get/search/tweets    
        String response = restTemplate.getForObject("https://api.twitter.com/1.1/search/tweets.json?q="+search, String.class);
        System.out.println("JSON Response From Twitter: "+response);

        model.addAttribute("jsonstring", response);
        model.addAttribute("username", username);

        return "json";
    }

}

添加模板以查看原始推文json.html

<!DOCTYPE html>
<html>
    <head>
        <title>JSON Tweets</title>
    </head>
    <body>
        <h3>Hello, <span th:text="${username}">Some User</span>!</h3>
        <div th:text="${jsonstring}">JSON Tweets</div>
    </body>
</html>

检查上述代码的完整项目和最新提交

于 2016-05-10T21:08:45.293 回答