如何从 Twitter Streaming API - POST statuses/filter 读取响应数据?我已建立连接并收到 200 状态代码,但我不知道如何阅读推文。我只想在推文到来时打印它们。
ws.url(url)
.sign(OAuthCalculator(consumerKey, requestToken))
.withMethod("POST")
.stream()
.map { response =>
if(response.headers.status == 200)
println(response.body)
}
Run Code Online (Sandbox Code Playgroud)
编辑:我找到了这个解决方案
ws.url(url)
.sign(OAuthCalculator(consumerKey, requestToken))
.withMethod("POST")
.stream()
.map { response =>
if(response.headers.status == 200){
response.body
.scan("")((acc, curr) => if (acc.contains("\r\n")) curr.utf8String else acc + curr.utf8String)
.filter(_.contains("\r\n"))
.map(json => Try(parse(json).extract[Tweet]))
.runForeach {
case Success(tweet) =>
println("-----")
println(tweet.text)
case Failure(e) =>
println("-----")
println(e.getStackTrace)
}
}
}
Run Code Online (Sandbox Code Playgroud) twitter scala playframework twitter-streaming-api playframework-2.5