如何从命令行使用JSON负载进行HTTP请求/调用?

68

如何从命令行执行JSON调用是最简单的方法?我有一个网站需要进行JSON调用以检索其他数据。

在Google Chrome中显示的请求负载(Request Payload)如下:

{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }

这是关于从(最好是)Linux命令行发起调用并检索JSON内容,而不是解析传入的JSON数据。

5个回答

101

您也可以使用wget:

wget -O- --post-data='{"some data to post..."}' \
  --header='Content-Type:application/json' \
  'http://www.example.com:9000/json'

使用选项-O并将-提供给它作为其值调用wget将导致wget将HTTP响应直接输出到标准输出而不是文件中(空格将被忽略,因此也可以写成-O -)。其长选项名称为--output-document=file


6
“-O-”是什么?这是一种烤肉串吗? - Slava Fomin II
从 man 页面得知,-O file--output-document=file 的简写选项,而破折号(-)通常表示当前 tty 标准输出的文件描述符。这只是意味着“将结果打印到控制台而不是写入文件”。 - Pius Raeder
2
谢谢。我的观点是这个参数看起来很神秘,我建议将这个解释添加到答案中 ;) - Slava Fomin II
1
@SlavaFominII 感谢您指出这一点。我已经更新了答案,加入了关于“-O”选项的解释。 - Pius Raeder

57

使用curl发送POST请求,类似于以下命令:

curl -X POST http://example.com/some/path -d '{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }'

如果你只是用 GET 方法检索数据,并且不需要发送任何内容,除了 URL 参数, 你只需运行 curl http://example.com/some/path


17
你可能需要加上“-H“Content-Type: application/json”这个参数。 - alanjds
HTTP/1.1 415 不支持的媒体类型 :-( - G. Sylvie Davies

13

您也可以使用wgetpost-file,我发现这很有用。

wget --post-file=[file] --header=Content-Type:application/json [URL]

您可以保留文件中的内容,并将内容作为post数据发送。


8
curl --request POST \
--url http://localhost:8099/someservice/services/boo \
--header 'authorization: Basic dkfhsdlepwmdseA==' \
--header 'cache-control: no-cache' \
--header 'content-type: application/json' \
--data '{"value": "24.127.1212.123"}'

-2

你看过curl吗?它非常擅长通过命令行方便地进行HTTP GET/POST请求。

例如(进行GET请求):

C:\WINDOWS>curl "http://search.twitter.com/search.json?q=twitterapi&result_type=
popular"
{"results":[{"from_user_id_str":"32316068","profile_image_url":"http://a2.twimg.
com/profile_images/351010682/twitblock_profile_normal.png","created_at":"Thu, 25
 Nov 2010 14:37:46 +0000","from_user":"twitblockapp","id_str":"7805146834669569"
,"metadata":{"result_type":"popular","recent_retweets":10},"to_user_id":null,"te
xt":"blocking and reporting functions are currently failing. @TwitterAPI have be
en notified. http://j.mp/id5w3m","id":7805146834669569,"from_user_id":32316068,"
geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href=&q
uot;http://twitter.com" rel="nofollow">Tweetie for Mac</a&g
t;"}],"max_id":9607558079713280,"since_id":0,"refresh_url":"?since_id=9607558079
713280&q=twitterapi","results_per_page":15,"page":1,"completed_in":0.012698,"sin
ce_id_str":"0","max_id_str":"9607558079713280","query":"twitterapi"}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接