我需要根据地理位置直播Feed。通过Twitter API文档,我了解到我们可以基于geolocaion进行搜索。
但是有可能根据地理位置进行流式传输吗?我使用spring social twitter进行API集成。
public function index()
{
$this->load->model("testmodel");
$data['records'] = $this->model->getAllRecords();
$this->load->view("edit",array('data'=>$data));
}
我看到Twitter流API也有一个请求的位置参数。但我如何使用Spring Social Twitter实现它。
由于
答案 0 :(得分:1)
我一直在尝试这个,最后得到了流媒体推文。 我继续学习本教程 - https://spring.io/guides/gs/accessing-twitter。
访问http://localhost:8080/stream/10_000将在旧金山地区发送推文(截至目前已硬编码),在控制台中播放10秒,并在10秒后在网页中显示这些推文。
在Controller类中添加一个@RequestMapping方法,如下所示:
HelloController.java
@RequestMapping("/stream/{time}")
public String streamTweet(@PathVariable int time, Model model) throws InterruptedException{
if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
return "redirect:/connect/twitter";
}
Model returnedmodel = streamService.streamApi(model, time);
model = returnedmodel;
return "stream";
}
StreamService.java
@Service
public class StreamService {
private final Logger log = LoggerFactory.getLogger(StreamService.class);
@Autowired
private Twitter twitter;
public Model streamApi(Model model, int time) throws InterruptedException{
List<Tweet> tweets = new ArrayList<>();
List<StreamListener> listeners = new ArrayList<StreamListener>();
StreamListener streamListener = new StreamListener() {
@Override
public void onWarning(StreamWarningEvent warningEvent) {
// TODO Auto-generated method stub
}
@Override
public void onTweet(Tweet tweet) {
System.out.println(tweet.getUser().getName() + " : " + tweet.getText());
log.info("User '{}', Tweeted : {}", tweet.getUser().getName() , tweet.getText());
tweets.add(tweet);
model.addAttribute("tweets", tweets);
}
@Override
public void onLimit(int numberOfLimitedTweets) {
// TODO Auto-generated method stub
}
@Override
public void onDelete(StreamDeleteEvent deleteEvent) {
// TODO Auto-generated method stub
}
};
listeners.add(streamListener);
//This sets the GeoCode (-122.75,36.8,-121.75,37.8) of San Francisco(South-West and North-East) region as given in below twitter docs
//https://dev.twitter.com/streaming/overview/request-parameters#locations
Float west=-122.75f;
Float south=36.8f;
Float east=-121.75f;
Float north = 37.8f;
FilterStreamParameters filterStreamParameters = new FilterStreamParameters();
filterStreamParameters.addLocation(west, south, east, north);
Stream userStream = twitter.streamingOperations().filter(filterStreamParameters, listeners);
Thread.sleep(time);
userStream.close();
return model;
}
}
stream.html
<html>
<head>
<title>Hello Twitter Stream</title>
</head>
<body>
<h4>The Twitter Stream:</h4>`enter code here`
<ul>
<li th:each="tweet:${tweets}"
th:text="${tweet.text} + ' tweeted by - ' + ${tweet.user.name}
+ ' from ' + ${tweet.user.location}
+ ' @ ' + ${tweet.createdAt}">
Tweet
</li>
</ul>
</body>
</html>
PS:我知道你不想做这样的事情(即在等待X秒之后显示推文,我只是这样做才能使这个工作)
顺便说一句,如果您有任何想法我如何使用此流来实时显示推文,(使用或不使用websockets)请分享。感谢。