Groovy POST 大量内容使用 HttpURLConnection

Groovy POST large content using HttpURLConnection

我有以下代码,用于向 REST API 端点发出 POST 请求以更新 SAP 应用程序数据。

#!/usr/bin/env groovy
import groovy.json.JsonSlurper

def call(total_record, url, bearer_token, scriptId, payload)  {

    Integer tot = total_record as Integer // Convert string to Integer
    HttpURLConnection connection = null;
    if (tot == 1) {
        StringBuilder stringBuilder = new StringBuilder("${url}");
        stringBuilder.append(URLEncoder.encode("${scriptId}", "UTF-8"))
        URL put_url = new URL(stringBuilder.toString());
        connection = (HttpURLConnection) put_url.openConnection()
        connection.setRequestMethod("PUT");
        println("Executing PUT")
    }
    else if (tot == 0) {
        URL post_url = new URL("${url}");
        connection = (HttpURLConnection) post_url.openConnection()
        connection.setRequestMethod("POST");
        println("Executing POST")
    }
    else {
        println("Total records can not be calculated")
    }
    connection.setRequestProperty("Authorization", bearer_token);
    connection.setRequestProperty("Content-Type", "application/json;odata=verbose")
    connection.setRequestProperty("Accept", "application/json")
    connection.setDoOutput(true)
    OutputStream pos = connection.getOutputStream()
    pos.write(payload.getBytes())
    pos.flush();
    pos.close();
    println(connection.responseCode)
    def msg = null
    if(connection.responseCode == 200){
        msg = "Executing Deployment"
    }
    else{
        msg = "Error is Connection\n"
        msg += connection.responseCode
    }
    connection.disconnect()
    return msg
}

读取 script/file 内容作为输入

File f = new File("out.py")
def content = f.readLines().toString()

示例负载:

String payload = """{
                            "Definition": {
                            "name": "filename",
                            "modifiedBy": "user_name",
                            "active": true,
                            "systemId": "filename_sid",
                            "script": "${content}"

                            }
                        }"""

基本上,我想上传一些python脚本内容(python代码)到API端点url。

当我只是 post 任何非代码的随机文本时,上面的代码运行良好。

但是当它读取文件内容时给出 400 Bad Request 作为 code.Example 错误如下:

我的脚本文件包含:

import clr
import sys
import System

# Testing Changes Priyabrata
clr.AddReference("System.Core")
clr.ImportExtensions(System.Linq)
clr.AddReference('System.Xml')
from System import DateTime, Random
Offeringid = ""
tableInfo = SqlHelper.GetTable("COMPOSIOTION")

错误响应如下:

{"error":{"code":"110000","message":"One or more fields in the API request contains invalid data. See the log for more information","target":"/api/script/v1/globalscripts/37","details":[{"code":"110000","message":"ScriptDefinition.Script: After parsing a value an unexpected character was encountered: S. Path 'ScriptDefinition.Script', line 13, position 18."}],"internalMessage":"Model validation failed"}}

然而,当我尝试在 Python 中编码时,脚本内容也使用 python 请求模块 posted 到端点。

但这会产生错误,即 groovy 中的 400 Bad Request。 我需要根据组织标准在 groovy 中制作管道。

enter image description here 任何建议将不胜感激。谢谢。

您的 POST 代码没问题。

问题不在于内容大小,而在于您构建 json 有效负载的方式。

你在 content

中有双引号

所以,使用字符串插值 json 构建如下:

def content = 'println "world"'
def payload = """{ "script":"${content}" }"""

会给你不正确的 json:

{ "content": "println "world"" }

最好使用 groovy.json.JsonBuildergroovy.json.JsonOutput

def content = 'println "world"'
def payload = new groovy.json.JsonBuilder([
    'active': true,
    'script': content 
]).toPrettyString()

这将得到格式正确的 json,其中包含所有必需的转义双引号和其他特殊字符

{
    "active": true,
    "script": "println \"world\""
}