Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用cURL发布JSON数据?_Json_Rest_Spring Mvc_Curl_Http Headers - Fatal编程技术网

如何使用cURL发布JSON数据?

如何使用cURL发布JSON数据?,json,rest,spring-mvc,curl,http-headers,Json,Rest,Spring Mvc,Curl,Http Headers,我使用Ubuntu并安装在上面。我想用cURL测试我的springrest应用程序。我在Java端编写了我的POST代码。但是,我想用cURL来测试它。我试图发布一个JSON数据。示例数据如下所示: {"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Config

我使用Ubuntu并安装在上面。我想用cURL测试我的springrest应用程序。我在Java端编写了我的POST代码。但是,我想用cURL来测试它。我试图发布一个JSON数据。示例数据如下所示:

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
我使用以下命令:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx
curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server
它返回以下错误:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
错误描述如下:

服务器拒绝了此请求,因为请求实体的格式不受请求方法()的请求资源的支持

Tomcat日志: “POST/ui/webapp/conf/clear HTTP/1.1”415 1051

cURL命令的正确格式是什么

这是我的Java端
PUT
code(我已经测试了GET和DELETE,它们可以正常工作):


您需要将内容类型设置为application/json。但是(或
--data
)发送内容类型
application/x-www-form-urlencoded
,Spring不接受该类型

查看,我认为您可以使用(或
--header
):

完整示例:

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"username":"xyz","password":"xyz"}' \
  http://localhost:3000/api/login
-H
--标题的缩写,
-d
--数据的缩写)

请注意,如果使用
-d
,则
-request POST
是可选的,因为
-d
标志表示POST请求



在Windows上,情况略有不同。查看注释线程。

尝试将数据放入文件中,比如说
body.json
,然后使用

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf

我也遇到了同样的问题。我可以通过指定

-H "Content-Type: application/json; charset=UTF-8"

您可能会发现resty很有用:

它是一个包装器,简化了命令行REST请求。您可以将它指向API端点,并提供PUT和POST命令。(示例改编自主页)

$restyhttp://127.0.0.1:8080/data #将resty设置为指向端点
$GET/blogs.json#GEThttp://127.0.0.1:8080/data/blogs.json
#放置JSON
$PUT/blogs/2.json'{“id”:2,“title”:“updated post”,“body”:“This is new.”
#从文件发布JSON
$POST/blogs/5.json

此外,通常仍然需要添加内容类型标题。不过,您可以这样做一次,以设置每个站点每个方法添加配置文件的默认值:

它对我有用,使用:

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost/api/postJsonReader.do
它很高兴地映射到Spring控制器:

@RequestMapping(value = "/postJsonReader", method = RequestMethod.POST)
public @ResponseBody String processPostJsonData(@RequestBody IdOnly idOnly) throws Exception {
        logger.debug("JsonReaderController hit! Reading JSON data!"+idOnly.getId());
        return "JSON Received";
}

i仅
是一个简单的id属性。

这对我来说效果很好,另外还使用了基本身份验证:

curl -v --proxy '' --basic -u Administrator:password -X POST -H "Content-Type: application/json"
        --data-binary '{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}'
        http://httpbin.org/post
当然,在没有SSL和已检查证书的情况下,您永远不应该使用基本身份验证

今天我再次遇到这个问题,使用Cygwin的cURL 7.49.1 for Windows。。。当使用带有JSON参数的
--data
--data binary
时,cURL会感到困惑,并将JSON中的
{}
解释为URL模板。添加一个
-g
参数来关闭cURL globbing修复了这个问题


另请参见。

我正在使用以下格式对web服务器进行测试

use -F 'json data'
让我们假设这种JSON dict格式:

{
    'comment': {
        'who':'some_one',
        'desc' : 'get it'
    }
}
完整示例
如果您正在针对RESTful接口测试大量JSON发送/响应,那么您可能希望查看Chrome插件(它允许您手动定义web服务测试)及其基于Node.js的命令行伙伴(它允许您针对Postman测试的“集合”进行自动化测试)。免费和开放

对于Windows,对
-d
值使用单引号对我不起作用,但在更改为双引号后它确实起作用。我还需要在花括号内转义双引号

也就是说,以下各项不起作用:

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path
但以下措施奏效了:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path

使用卷曲窗口,尝试以下操作:

curl -X POST -H "Content-Type:application/json" -d "{\"firstName\": \"blablabla\",\"lastName\": \"dummy\",\"id\": \"123456\"}" http-host/_ah/api/employeeendpoint/v1/employee

这对我很有效

curl -X POST --data @json_out.txt http://localhost:8080/
在哪里,

-X
表示http动词


--data
表示要发送的数据。

例如,创建一个JSON文件params.JSON,并将此内容添加到其中:

[
    {
        "environment": "Devel",
        "description": "Machine for test, please do not delete!"
    }
]
然后运行以下命令:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx
curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server
这对我很有用:

curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json

您还可以将JSON内容放入文件中,并通过标准输入使用
--upload file
选项将其传递给curl,如下所示:

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
您可以使用其直观的GUI来组装
cURL
命令

  • 安装并启动邮递员
  • 键入URL、帖子正文、请求标题等。pp
  • 单击
    code
  • 从下拉列表中选择
    cURL
  • 复制并粘贴
    cURL
    命令
  • 注意:下拉列表中有几个自动生成请求的选项,这就是为什么我认为我的帖子首先是必要的。

    是推荐的
    curl
    的替代方案,因为你可以

    $ http POST http://example.com/some/endpoint name=value name1=value1
    
    默认情况下,它讲JSON,并将为您设置必要的头以及将数据编码为有效的JSON。还有:

    Some-Header:value
    
    用于标题,以及

    name==value
    
    用于查询字符串参数。如果您有一大块数据,也可以从文件中读取,并对其进行JSON编码:

     field=@file.txt
    

    您可以将所需格式的扩展名作为url的结尾传递。 比如.json

    .xml


    注意:您需要在pom中添加jackson和jaxb maven依赖项。

    使用-d选项添加负载

    curl -X POST \
    http://<host>:<port>/<path> \
    -H 'Accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{
    "foo": "bar",
    "lorem": "ipsum"
    }'
    
    curl-X POST\
    http://:\
    -H'Accept:application/json'\
    -H'内容类型:应用程序/json'\
    -d'{
    “foo”:“bar”,
    “知识”:“ipsum”
    }'
    
    此外:

    使用-X POST来使用POST方法

    使用-H“Accept:application/json”添加Accept类型头

    使用-H“Content-Type:application/json”添加内容类型标题

    我为此制作了一个工具。它可以发送请求并格式化curl代码段:

    下面是一个例子:

    示例输出:

    curl -XGET -H "Accept: application/json" -d "{\"value\":\"30\",\"type\":\"Tip 3\",\"targetModule\":\"Target 3\",\"configurationGroup\":null,\"name\":\"Configuration Deneme 3\",\"description\":null,\"identity\":\"Configuration Deneme 3\",\"version\":0,\"systemId\":3,\"active\":true}" "http://localhost:8080/xx/xxx/xxxx"
    

    您可以使用postman转换为CURL


    这对我在Windows10上的工作很有效

    curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X  PUT http://localhost:8080/api/changeowner/CAR4
    

    如果要包含动态数据,这里还有另一种方法

    #!/bin/bash
    
    version=$1
    text=$2
    branch=$(git rev-parse --abbrev-ref HEAD)
    repo_full_name=$(git config --get remote.origin.url | sed 's/.*:\/\/github.com\///;s/.git$//')
    token=$(git config --global github.token)
    
    generate_post_data()
    {
      cat <<EOF
    {
      "tag_name": "$version",
      "target_commitish": "$branch",
      "name": "$version",
      "body": "$text",
      "draft": false,
      "prerelease": false
    }
    EOF
    }
    
    echo "Create release $version for repo: $repo_full_name branch: $branch"
    curl --data "$(generate_post_data)" "https://api.github.com/repos/$repo_full_name/releases?access_token=$token"
    
    #/bin/bash
    版本=$1
    特克斯
    
      send-webhook-callback-once-deployment-ready:
        name: Invoke webhook callback url defined by the customer (Ubuntu 18.04)
        runs-on: ubuntu-18.04
        needs: await-for-vercel-deployment
        steps:
          - uses: actions/checkout@v1 # Get last commit pushed - See https://github.com/actions/checkout
          - name: Expose GitHub slug/short variables # See https://github.com/rlespinasse/github-slug-action#exposed-github-environment-variables
            uses: rlespinasse/github-slug-action@v3.x # See https://github.com/rlespinasse/github-slug-action
          - name: Expose git environment variables and call webhook (if provided)
            # Workflow overview:
            #  - Resolves webhook url from customer config file
            #  - If a webhook url was defined, send a
            run: |
              MANUAL_TRIGGER_CUSTOMER="${{ github.event.inputs.customer}}"
              CUSTOMER_REF_TO_DEPLOY="${MANUAL_TRIGGER_CUSTOMER:-$(cat vercel.json | jq --raw-output '.build.env.NEXT_PUBLIC_CUSTOMER_REF')}"
    
              VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK=$(cat vercel.$CUSTOMER_REF_TO_DEPLOY.staging.json | jq --raw-output '.build.env.VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK')
    
              # Checking if a webhook url is defined
              if [ -n "$VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK" ]; then
                # Run script that populates git-related variables as ENV variables
                echo "Running script populate-git-env.sh"
                . ./scripts/populate-git-env.sh
    
                echo "Resolved git variables:"
                echo "'GIT_COMMIT_SHA': $GIT_COMMIT_SHA"
                echo "'GIT_COMMIT_REF': $GIT_COMMIT_REF"
                echo "'GIT_COMMIT_TAGS': $GIT_COMMIT_TAGS"
    
                # Generates JSON using a bash function - See https://stackoverflow.com/a/57369772/2391795
                # "End Of File" must be at the beginning of the line with no space/tab before or after - See https://stackoverflow.com/a/12909284/2391795
                # But, when executed by GitHub Action, it must be inside the "run" section instead
                generate_post_data() {
                  cat <<EOF
                {
                  "MANUAL_TRIGGER_CUSTOMER": "${MANUAL_TRIGGER_CUSTOMER}",
                  "CUSTOMER_REF": "${CUSTOMER_REF_TO_DEPLOY}",
                  "STAGE": "staging",
                  "GIT_COMMIT_SHA": "${GIT_COMMIT_SHA}",
                  "GIT_COMMIT_REF": "${GIT_COMMIT_REF}",
                  "GIT_COMMIT_TAGS": "${GIT_COMMIT_TAGS}",
                  "GITHUB_REF_SLUG": "${GITHUB_REF_SLUG}",
                  "GITHUB_HEAD_REF_SLUG": "${GITHUB_HEAD_REF_SLUG}",
                  "GITHUB_BASE_REF_SLUG": "${GITHUB_BASE_REF_SLUG}",
                  "GITHUB_EVENT_REF_SLUG": "${GITHUB_EVENT_REF_SLUG}",
                  "GITHUB_REPOSITORY_SLUG": "${GITHUB_REPOSITORY_SLUG}",
                  "GITHUB_REF_SLUG_URL": "${GITHUB_REF_SLUG_URL}",
                  "GITHUB_HEAD_REF_SLUG_URL": "${GITHUB_HEAD_REF_SLUG_URL}",
                  "GITHUB_BASE_REF_SLUG_URL": "${GITHUB_BASE_REF_SLUG_URL}",
                  "GITHUB_EVENT_REF_SLUG_URL": "${GITHUB_EVENT_REF_SLUG_URL}",
                  "GITHUB_REPOSITORY_SLUG_URL": "${GITHUB_REPOSITORY_SLUG_URL}",
                  "GITHUB_SHA_SHORT": "${GITHUB_SHA_SHORT}"
                }
              EOF
                }
    
                echo "Print generate_post_data():"
                echo "$(generate_post_data)"
    
                echo "Calling webhook at '$VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK'"
                echo "Sending HTTP request (curl):"
                curl POST \
                  "$VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK" \
                  -vs \
                  --header "Accept: application/json" \
                  --header "Content-type: application/json" \
                  --data "$(generate_post_data)" \
                  2>&1 | sed '/^* /d; /bytes data]$/d; s/> //; s/< //'
    
                # XXX See https://stackoverflow.com/a/54225157/2391795
                # -vs - add headers (-v) but remove progress bar (-s)
                # 2>&1 - combine stdout and stderr into single stdout
                # sed - edit response produced by curl using the commands below
                #   /^* /d - remove lines starting with '* ' (technical info)
                #   /bytes data]$/d - remove lines ending with 'bytes data]' (technical info)
                #   s/> // - remove '> ' prefix
                #   s/< // - remove '< ' prefix
    
              else
                echo "No webhook url defined in 'vercel.$CUSTOMER_REF_TO_DEPLOY.staging.json:.build.env.VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK' (found '$VERCEL_DEPLOYMENT_COMPLETED_WEBHOOK')"
              fi