使用Curl在scala中传递Json字符串时出错

时间:2017-09-16 18:35:52

标签: json scala curl post

我试图在scala中使用curl发布一个json字符串。我的curl命令在linux框中执行时工作正常,但是总是从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字符串(pay load)复制到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

第3步:

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

第4步:

cmd.!!

我收到以下错误

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

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

1 个答案:

答案 0 :(得分:0)

我怀疑你的问题是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中产生卷曲并建议使用现有的http客户端库(我个人喜欢Gigahorse)。