Skip to content

Instantly share code, notes, and snippets.

@cliff76
Created September 18, 2017 05:53
Show Gist options
  • Select an option

  • Save cliff76/2fe8c5a92aeaa73f03cc2368a3b40c7f to your computer and use it in GitHub Desktop.

Select an option

Save cliff76/2fe8c5a92aeaa73f03cc2368a3b40c7f to your computer and use it in GitHub Desktop.
Authenticated Twitter Request
import groovy.json.*
def bearerToken
slurper = new JsonSlurper()
def getToken() {
def twigglerKey = 'enter-key-here'
def twigglerSecret = 'enter-secret-here'
def encodedToken = URLEncoder.encode(twigglerKey) + ':' + URLEncoder.encode(twigglerSecret)
encodedToken = new String(Base64.encoder.encode(encodedToken.bytes))
def connection = new URL('https://api.twitter.com/oauth2/token').openConnection()
connection.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
connection.setRequestProperty('Authorization', 'Basic ' + encodedToken)
connection.method = 'POST'
connection.doOutput = true
connection.outputStream.withStream { it << 'grant_type=client_credentials'.bytes }
def json
connection.inputStream.withStream { json = slurper.parseText(it.text) }
return json."access_token"
}
bearerToken = getToken()
def connection = new URL('https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi').openConnection()
connection.setRequestProperty('Authorization', 'Bearer ' + bearerToken)
def response
connection.inputStream.withStream { response = slurper.parseText(it.text) }
println response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment