【问题标题】:Error while Passing Json string in scala using Curl使用Curl在scala中传递Json字符串时出错
【发布时间】:2017-09-16 18:35:52
【问题描述】:

我正在尝试在 scala 中使用 curl 发布一个 json 字符串。如果从 linux 机器执行,我的 curl 命令可以正常工作,但总是从 scala 发出错误((“消息”:“必须提供查询字符串。”,)。

我在 linux 中的 curl 命令:

 curl http://laptpad1811:5000/graphql -H "Content-Type: application/json"  
    -X POST -d '{"query":"mutation 
    CreateFileReceivedEvent($createFileReceivedEventInput: 
    CreateFleReceivedEventInput!) {  createFileReceivedEvent(input: 
    $createFileReceivedEventInput) {    clientMutationId  }}","variables":
    {"createFileReceivedEventInput":
    {"clientMutationId":"Test","fileReceivedEvent":{"file":
    {"fileTrackingId":"83a86c44-66a5-4de0-9b7f-
    c6995877279d","name":"textfile_2017-08-21T15:58:45Z","fileType":
    {"code":"textfile"}},"eventTimestamp":"2017-08-
    21T15:59:30Z"}}},"operationName":"CreateFileReceivedEvent"}'

我的 scala 代码: step1:将整个json字符串(有效负载)复制到txt文件

 '{"query":"mutation CreateFileReceivedEvent($createFileReceivedEventInput: 
    CreateFleReceivedEventInput!) {  createFileReceivedEvent(input: 
    $createFileReceivedEventInput) {    clientMutationId  }}","variables":
    {"createFileReceivedEventInput":
    {"clientMutationId":"Test","fileReceivedEvent":{"file":
    {"fileTrackingId":"83a86c44-66a5-4de0-9b7f-
    c6995877279d","name":"textfile_2017-08-21T15:58:45Z","fileType":
    {"code":"textfile"}},"eventTimestamp":"2017-08-
    21T15:59:30Z"}}},"operationName":"CreateFileReceivedEvent"}'

第二步:

 val data=fromFile("/usr/test/data.txt").getLines.mkString

第三步:

val cmd = Seq("curl", "http://laptpad1811:5000/graphql", "-H",
  "'Content-Type:application/json'" ,"-X", "POST", "-d" , data)

第四步:

cmd.!!

我收到以下错误

String =
"{
  "errors": [
    {
      "message": "Must provide query string.",
      "stack": "BadRequestError: Must provide query string.\n

我尝试将 " 更改为 ' 和 json 字符串的多个组合,但我总是得到相同的错误。

【问题讨论】:

    标签: json scala curl post


    【解决方案1】:

    我怀疑您的问题是 sys.process 没有通过 shell 传递命令(例如 bash),因此 shell 中必需的引号在 Scala 中变得不必要(并传递给在这种情况下的命令Unix 风格的实用程序可能会导致意外行为)。

    那就试试吧:

    val cmd = Seq("curl", "http://laptpad1811:5000/graphql", "-H", "Content-Type: application/json", "-X", "POST", "-d", data)
    

    同样从文本文件中删除单引号。

    但是,我建议不要在 Scala 中生成 curl,并建议使用现有的 http 客户端库之一(我个人喜欢 Gigahorse)。

    【讨论】:

    • 这行得通。删除引号有效。谢谢李维!!
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多