我正在使用scalaj发出Http发布请求
如何在 postData 字段中传递纬度、长度和半径作为参数
val result = Http("http:xxxx/xxx/xxxxx").postData("""{"latitude":"39.6270025","longitude":"-90.1994042","radius":"0"}""").asString
为什么字符串以这种方式传递"json"?
根据文档,postData 函数似乎只接受字节数组和字符串作为参数。
所以这同时是两个问题。让我们从第二个开始。
为什么字符串以这种方式传递"json"?
Scala 允许对多行字符串文字(或包含换行符、引号等的字符串(使用特殊语法。 所以你可以做
val s = """Welcome home!
How are you today?"""
现在回到主要问题
如何在 postData 字段中传递纬度、长度和半径作为参数?
我想你处于这种情况:
val lat = "39.6270025"
val long = "-90.1994042"
你想把它传递到postData
函数中,与其他一些可能固定的字符串混合在一起。
那么Scala给出的另一个功能是所谓的string interpolation
。 简单的例子
val name = "Mark" // output on the REPL would be: name: String = Mark
val greeting = s"Hello $name!" // output on the REPL would be: greeting: String = Hello Mark!
所以在你的情况下,你也可以做同样的事情
val result = Http("http:xxxx/xxx/xxxxx")
.postData(s"""{"latitude":$lat,"longitude":$long,"radius":"0"}""")
.asString