从JSON文件中读取标题,并使用SCALA中的Play在API调用中设置为标题的元组
我有Json文件,它有这样的标题和正文: 文件名:test.json
{
"request": {
"headers" : {
"Provider":"1122321",
"Authorization":"44444444",
"Agent":"Web",
"Content-Type":"application/json"
}
"body":{
}
}
}
现在我要做的是,从Json文件中读取Body和Headers以及稍后在调用API时使用,我正在使用播放WS和Play JSON(2.5.x),但我无法获取并设置标题:
下面是我的代码,目前我有硬编码标题,但我需要从JSON获取和设置,我试过的一种方法是在元组列表中添加标题并使用,但我无法弄清楚我是怎么做的可以从JSON文件中获取标头并将它们转换为元组列表
val file = new File("E:\\test.json")
val fileIn = new FileInputStream(file)
val json: JsValue = Json.parse(fileIn)
val jsonbody = (json \ "data" \ "request" \"body").get
val jsonheader = (json \ "data" \ "request" \"headers").get
println(jsonheader)
// {"Provider":"1122321","Authorization":"44444444","Agent":"Web","Content-Type":"application/json"}
var url: String = "http://test.com/api/test"
// wsClient.url(url2).withHeaders("Provider"->"1122321", "Authorization" ->` "44444444", "Agent" -> "Web", "Content-Type" -> "application/json", "ClientVersion" -> "3").post(jsonbody).map { response =>
val resbody1: String = response.body
val resstatus1: String = response.statusText
}
答案 0 :(得分:0)
我能够实现我的目标,但我知道这不是一种有效的方式,如果有人能帮我改进,我将非常感激:
val file = new File("E:\\test.json")
val fileIn = new FileInputStream(file)
val json: JsValue = Json.parse(fileIn)
val jsonbody = (json \ "data" \ "request" \"body").get
val jsonheader = (json \ "data" \ "request" \"headers").get
println(jsonheader)
// {"Provider":"1122321","Authorization":"44444444","Agent":"Web","Content-Type":"application/json"}
val jsonheaderlist = jsonheader.toString().substring(1, jsonfile.headersval.toString().length - 1)
.split(",")
.map(_.split(":"))
.map { case Array(k, v) => (k.substring(1, k.length-1), v.substring(1, v.length-1))}
.toMap.toList
var url: String = "http://test.com/api/test"
var req = wsClient.url(url)
jsonheaderlist.foreach{case(value)=>
req = req.withHeaders(value)
}
req = req.post(jsonbody).map { response =>
val resbody1: String = response.body
val resstatus1: String = response.statusText
}