2017-08-29 369 views
2

我必須在我的應用程序中插入許多數據,並且通過圖形界面需要很多時間。出於這個原因,我想創建一個bash腳本並通過使用REST API進行curl請求(我必須手動指定id)。通過bash腳本執行curl請求

問題是我得到錯誤:服務器拒絕了這個請求,因爲請求實體的格式不是所請求方法的請求資源所支持的格式。

下面是代碼

#!/bin/bash 

for i in {1..1} 
do                                             
CURL='/usr/bin/curl -X POST' 
RVMHTTP="http://192.168.1.101:8080/sitewhere/api/devices 
    -H 'accept:application/json' 
    -H 'content-type:application/json' 
    -H 'x-sitewhere-tenant:sitewhere1234567890' 
    --user admin:password" 

DATA=" -d '{\"hardwareId":\"$i",\"siteToken\":\"4e6913db-c8d3-4e45-9436-f0a99b502d3c\",\"specificationToken\":\"82043707-9e3d-441f-bdcc-33cf0f4f7260\"}'" 

# or you can redirect it into a file: 
$CURL $RVMHTTP $DATA >> /home/bluedragon/Desktop/tokens 
done 

我的請求的格式必須被JSON

+0

順便說一句 - http://shellcheck.net/是一個資源,你可能會覺得有用;嘗試修復它發現的內容(並且在您不瞭解建議背後的原因/建議似乎使事情變得更糟時,閱讀與每個錯誤鏈接的維基頁面),然後再提問。 –

回答

3
#!/usr/bin/env bash 

rvmcurl() { 
    local url 
    url="http://192.168.1.101:8080/sitewhere/${1#/}" 
    shift || return # function should fail if we weren't passed at least one argument 
    curl -XPOST "${rvm_curl_args[@]}" "$url" "[email protected]" 
} 

i=1 # for testing purposes 

rvm_curl_args=(
    -H 'accept:application/json' 
    -H 'content-type:application/json' 
    -H 'x-sitewhere-tenant:sitewhere1234567890' 
    --user admin:password 
) 

data=$(jq -n --arg hardwareId "$i" ' 
{ 
     "hardwareId": $hardwareId, 
     "siteToken": "4e6913db-c8d3-4e45-9436-f0a99b502d3c", 
     "specializationToken": "82043707-9e3d-441f-bdcc-33cf0f4f7260" 
}') 

rvmcurl /api/devices -d "$data" 

注:旨在被解析

  • 命令,或命令片段成多個詞,應該從不 b e存儲在字符串中。改爲使用數組或函數。這樣的字符串內部的引號不會被解析爲語法,而是(在沒有eval的情況下進行解析時,它攜帶它自己的serious risks and caveats)變成字面值。有關完整說明,請參閱BashFAQ #50
  • 使用支持JSON的工具(如jq)確保生成的數據是合法的JSON。
  • 二進制文件的完全限定路徑通常是反模式。它不會導致顯着的性能提升(shell緩存PATH查找),但它會減少腳本的可移植性和靈活性(阻止您在PATH中,在導出的shell函數中安裝curl的包裝器,或者除此以外)。
  • 全大寫變量名稱位於命名空間used for variables with meaning to the shell and operating system中。使用至少包含一個小寫字母的名稱作爲自己的變量,以防止發生衝突。
+0

很漂亮 –

+0

現在問題是http狀態400 - incompleteData:並非提供了所有必需的數據。 這裏是我想請求(從郵遞員兩者),它適用於郵差,如果在慶典 捲曲-X POST http://192.168.1.101:8080/sitewhere/api/devices 直接插入-H'accept:application/json' -H'content-type:application/json' -H'x-sitewhere-tenant:sitewhere1234567890' --user admin:password -d'{ 「hardwareId」: 「XXX」, 「siteToken」: 「4e6913db-c8d3-4e45-9436-f0a99b502d3c」, 「specificationToken」: 「82043707-9e3d-441f-bdcc-33cf0f4f7260」 }」 –

+0

運行'的bash -x yourscript',和比較它在lo中發出的命令克到你想要的。 –