2014年12月13日土曜日

groovyとshipyardでservice keyを取得する

groovyとshipyardでservice keyを取得するには、以下のサンプルコードのようにloginを実施してからservicekeysでservice keyを取得します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.6')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import org.apache.http.auth.*
import org.apache.http.entity.*
import groovy.json.*

def host = "192.168.1.212" // replace this
def port = 8080
def authToken

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {

  def method = new HttpPost(
    "http://${host}:${port}/auth/login"
  )
  def json = new JsonBuilder()
  json (
    "username":"admin", "password":"shipyard"
  )
  method.setHeader("Content-Type", "application/json; charset=utf-8")
  method.setEntity(new StringEntity(json.toString(), "UTF-8"))
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()
  def rjson = new JsonSlurper().parseText(response.getEntity().getContent().text)
  authToken = rjson.auth_token
  println "auth token:${authToken}"

  def method2 = new HttpPost(
    "http://${host}:${port}/api/servicekeys"
  )
  def json2 = new JsonBuilder()
  json2 (
    description:"test key"
  )
  method2.setHeader("Content-Type", "application/json; charset=utf-8")
  method2.setHeader("X-Access-Token", "admin:" + authToken)
  method2.setEntity(new StringEntity(json2.toString(), "UTF-8"))

  def response2 = httpclient.execute(method2)
  println response2.getStatusLine().getStatusCode()
  def rjson2 = new JsonSlurper().parseText(response2.getEntity().getContent().text)
  println "service key:${rjson2.key}"

}

0 件のコメント:

コメントを投稿