2017-09-16 45 views
0

我想在scala中使用curl發佈json字符串。如果從Linux框,但陣痛錯誤((「消息」執行我的curl命令工作得很好:「必須提供的查詢字符串。」)總是從斯卡拉在linux使用捲曲在scala中傳遞Json字符串時發生錯誤

我的工作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代碼: 第一步:複製整個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字符串的多發組合,但我總是得到相同的錯誤。

回答

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)。

+0

這工作。刪除引用工作。謝謝Levi! –