![](/img/trans.png)
[英]How can I set a CoAP post request Body with a requestparameter and a File?
[英]How i can send file in body of the post request? groovy
我有一個文件作為字節數組。 我想在發布請求的正文中發送它。
我在 JavaScript 中有一個很好的例子。 不能在 groovy 中重復相同的代碼。 服務器返回“初始服務器錯誤”。 我確定問題出在傳遞的數據類型上。
Groovy 代碼:
def reqParams = [:];
reqParams.filename = 'test.pdf'
reqParams.filedata = utils.readFileContent(obj.clientFile) // array of byte
reqParams.destination = 'test'
def jsonBody = new JsonBuilder(reqParams).toString()
// build HTTP POST
def client = new RESTClient(baseUrl)
client.auth.basic 'user1', 'user1'
def resp = client.post(body : jsonBody, contentType: JSON)
使用幫助 JS 生成請求的示例正文:
Content-Type: multipart/form-data; boundary=--------------------------295349461296500421390407
Content-Length: 659
----------------------------295349461296500421390407
Content-Disposition: form-data; name="filedata"; filename="query.txt"
<query.txt>
----------------------------295349461296500421390407
Content-Disposition: form-data; name="destination"
workspace://SpacesStore/716afb88-715a-4413-85bc-f71630abfd51
----------------------------295349461296500421390407
Content-Disposition: form-data; name="filename"
jasperTextToNextStrin.txt
----------------------------295349461296500421390407--
如何使用 Groovy 發送 POST 請求?
JSON 格式本身不支持二進制數據。 要在 JSON 有效負載中發送二進制數據,您需要以某種方式將其編碼為文本。
您應該使用什么編碼取決於服務器的期望。
常見的編碼是base 64 編碼:
reqParams.filedata = myFile.bytes.encodeBase64().toString()
或者
reqParams.filedata = utils.readFileContent(obj.clientFile).encodeBase64().toString()
如果readFileContent
確實返回一個byte[]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.