Jak opublikować dane JSON za pomocą cURL?
Używam Ubuntu i zainstalowałem na nimcURL . Chcę przetestować moją aplikację Spring REST z cURL. Napisałem swój kod pocztowy na stronie Java. Jednak chcę go przetestować za pomocą cURL. Próbuję opublikować dane JSON. Przykładowe dane są takie:
{"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}
Używam polecenia:
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
Zwraca ten błąd:
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
Opis błędu jest następujący:
serwer odmówił tego żądania, ponieważ jednostka żądania jest w formacie Nie wspierane przez żądany zasób dla żądanej metody ().
Tomcat log: "POST / UI / webapp/conf/clear HTTP / 1.1" 415 1051
Jaki jest właściwy format polecenia cURL?
To jest moja strona Javy PUT
Kod (przetestowałem GET i DELETE i działają):
@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
configuration.setName("PUT worked");
//todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
return configuration;
}
25 answers
Musisz ustawić content-type NA application / json. Ale -d
(or --data
) wysyła typ zawartości application/x-www-form-urlencoded
, który nie jest akceptowany po stronie Springa.
Patrząc na stronę podręcznika curl , myślę, że możesz użyć -H
(lub --header
):
-H "Content-Type: application/json"
Pełny przykład:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login
(-H
jest skrótem od --header
, -d
dla --data
)
Zauważ, że -request POST
jest opcjonalne Jeśli używasz -d
, ponieważ znacznik -d
implikuje żądanie POST.
On Okna, sprawy są nieco inne. Zobacz wątek komentarza.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-17 02:25:11
Spróbuj umieścić swoje dane w pliku, powiedz body.json
, a następnie użyj
curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-24 10:04:24
Dla Windows, posiadanie pojedynczego cudzysłowu dla wartości -d
nie działało dla mnie, ale działało po zmianie na podwójny cudzysłów. Musiałem też uciec od podwójnych cudzysłowów w nawiasach klamrowych.
Oznacza to, że nie działa:
curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path
Ale działa:
curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:51:04
Resty może Ci się przydać: https://github.com/micha/resty
Jest to owijarka okrągła, która upraszcza żądania odpoczynku z wiersza poleceń. Kierujesz go do punktu końcowego API, który udostępnia polecenia PUT I POST. (Przykłady zaadaptowane ze strony głównej)
$ resty http://127.0.0.1:8080/data #Sets up resty to point at your endpoing
$ GET /blogs.json #Gets http://127.0.0.1:8080/data/blogs.json
#Put JSON
$ PUT /blogs/2.json '{"id" : 2, "title" : "updated post", "body" : "This is the new."}'
# POST JSON from a file
$ POST /blogs/5.json < /tmp/blog.json
Ponadto często konieczne jest dodanie nagłówków typu treści. Można to jednak zrobić raz, aby ustawić domyślne dodawanie plików konfiguracyjnych według metody dla witryny: Ustawianie domyślnych opcji RESTY
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-08 14:34:39
U mnie zadziałało:
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost/api/postJsonReader.do
To było szczęśliwie odwzorowane do kontrolera sprężyny:
@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";
}
IdOnly
jest prostym POJO z właściwością id.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:47:50
Jako przykład utwórz plik JSON, params.json, i dodać do niego tę treść:
[
{
"environment": "Devel",
"description": "Machine for test, please do not delete!"
}
]
Następnie uruchom polecenie:
curl -v -H "Content-Type: application/json" -X POST --data @params.json -u your_username:your_password http://localhost:8000/env/add_server
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 16:05:09
Mam ten sam problem. Mogę to rozwiązać podając
-H "Content-Type: application/json; charset=UTF-8"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-15 15:45:09
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-30 06:43:36
Dobrze mi to wyszło.
curl -X POST --data @json_out.txt http://localhost:8080/
Gdzie,
-X
oznacza czasownik http.
--data
oznacza dane, które chcesz wysłać.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-01 14:31:40
Możesz użyć Postman z intuicyjnym interfejsem graficznym do złożenia cURL
polecenia.
- Install and Start Postman
- wpisz adres URL, treść wiadomości, nagłówki żądań itp. pp.
- Kliknij na
Code
- Wybierz
cURL
z listy rozwijanej - skopiuj i wklej swoje
cURL
polecenie
Uwaga: Istnieje kilka opcji automatycznego generowania żądań na rozwijanej liście, dlatego pomyślałem, że mój post był konieczny w pierwsze miejsce.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-25 12:47:20
Używając okna CURL, spróbuj tego:
curl -X POST -H "Content-Type:application/json" -d "{\"firstName\": \"blablabla\",\"lastName\": \"dummy\",\"id\": \"123456\"}" http-host/_ah/api/employeeendpoint/v1/employee
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-12 11:37:54
HTTPie jest zalecaną alternatywą dla curl
, ponieważ możesz zrobić tylko
$ http POST http://example.com/some/endpoint name=value name1=value1
Domyślnie mówi JSON i zajmie się zarówno ustawieniem niezbędnego nagłówka, jak i kodowaniem danych jako poprawnego JSON. Jest też:
Some-Header:value
Dla nagłówków i
name==value
Dla parametrów łańcucha zapytania. Jeśli masz dużą część danych, możesz je również odczytać z pliku, który ma być zakodowany w JSON:
[email protected]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-23 14:13:44
Jeśli testujesz wiele JSON send / responses przeciwko interfejsowi RESTful, możesz sprawdzić wtyczkę Postman dla Chrome (która pozwala ręcznie zdefiniować testy usług internetowych) i jej węzeł.oparty na js Newman command-line companion (który pozwala na automatyzację testów względem "zbiorów" testów Postmana.) Zarówno darmowe, jak i otwarte!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-14 21:40:23
To działało dobrze dla mnie, Dodatkowo przy użyciu podstawowego uwierzytelniania:
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
Oczywiście nigdy nie należy używać uwierzytelniania podstawowego bez SSL i sprawdzonego certyfikatu.
Natknąłem się dziś na to ponownie, używając cURL 7.49.1 Cygwina Dla Windows... A gdy użyjemy --data
lub --data-binary
z argumentem JSON, cURL pomylił się i zinterpretował {}
w JSON jako szablon URL. Dodanie argumentu -g
, aby wyłączyć globowanie loków, naprawiło to.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:49:25
Możesz również umieścić zawartość JSON w pliku i przekazać ją do curl za pomocą opcji --upload-file
poprzez standardowe wejście, Jak to:
echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-29 13:26:01
To mi pomogło:
curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-16 16:39:51
Oto inny sposób, aby to zrobić, jeśli masz dynamiczne dane do włączenia.
#!/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"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-06 06:02:43
Używam poniższego formatu do testowania z serwerem WWW.
use -F 'json data'
Załóżmy, że format JSON dict:
{
'comment': {
'who':'some_one',
'desc' : 'get it'
}
}
Pełny przykład
curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 21:50:02
Wiem, wiele odpowiedzi na to pytanie, ale chciałem się podzielić, gdzie miałem problem:
Curl-x POST http://your-server-end-point - H " Content-Type: application / json" -d @path-of-your-JSON-file.json
Widzisz, zrobiłem wszystko dobrze, tylko jedno - "@" przegapiłem przed ścieżką pliku JSON.
Znalazłem jeden odpowiedni dokument w Internecie - https://gist.github.com/subfuzion/08c5d85437d5d4f00e58
Mam nadzieję, że to może pomóc nielicznym. dzięki
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-28 14:14:25
Użyj opcji-d, aby dodać ładunek
curl -X POST \
http://<host>:<port>/<path> \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"foo": "bar",
"lorem": "ipsum"
}'
DODATKOWO:
Użyj -X POST aby użyć metody POST
Użyj -H 'Accept: application / json' aby dodać nagłówek typu accept
Use-H 'Content-Type: application/json' to add content type header
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-13 20:06:36
To działało dla mnie na Windows10
curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X PUT http://localhost:8080/api/changeowner/CAR4
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-23 14:37:07
Proszę sprawdzić to Narzędzie . Pomaga w łatwym tworzeniu urywków 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"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-27 12:35:04
Jeśli skonfigurujesz SWAGGER do swojej aplikacji spring boot i wywołasz dowolny API z aplikacji, możesz zobaczyć również to żądanie CURL.
Myślę, że jest to łatwy sposób generowania żądań poprzez CURL.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-28 12:06:54
Na podstawie https://stackoverflow.com/a/57369772/2391795 odpowiedź, oto co zrobiłem z tym na Githubie. To było trochę trudne ze względu na tag EOF
.
Moim celem było wysłanie połączenia HTTP po zakończeniu wdrożenia Vercel(podobnie jak webhook).
Mając nadzieję, że ten przykład z prawdziwego świata może pomóc innym ludziom.
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/[email protected] # 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-30 15:00:38
Możesz przekazać rozszerzenie formatu, który chcesz jako koniec adresu url. jak http://localhost:8080/xx/xxx/xxxx.json
Lub
Http://localhost:8080/xx/xxx/xxxx.xml
Uwaga: musisz dodać zależności jackson i jaxb maven w swoim pom.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-16 09:57:33