cma*_*han 8 rest curl ruby-on-rails http
我一直在玩使用HTTP POST调用我的rails控制器.我可以使用curl命令来实现它,给定一个名为item的模型和名为name的项目中的属性:
curl -X POST -d "<item><name>myname</name></item>" -H "Content-Type: text/xml" http://localhost:3000/items.xml
Run Code Online (Sandbox Code Playgroud)
我很好奇的是如何使用文本而不是xml作为我的内容类型进行相同的调用....我试过:
curl -X POST -d "name=myname" http://localhost:3000/items.xml
Run Code Online (Sandbox Code Playgroud)
但这似乎将'name'参数作为顶级范围传递; 所以它不会最终出现在控制器的参数中....
我是个菜鸟; 只是想了解如何以两种方式做到这一点....
谢谢!
Chr*_*ley 12
简短的回答,你需要
(a)将其发送为-H"内容类型:application/x-www-form-urlencoded".
(b)将参数指定为Object [field] = value - 例如User [name]将引用某个用户对象中的name字段.
(c)[Not required,因为你使用curl]编码参数并POST/PUT它们.
编码很简单,虽然curl会为你做,但理解它是有用的.我引用了W3C规范的摘录......"
应用程序/ x-WWW窗体-urlencoded
这是默认的内容类型.使用此内容类型提交的表单必须按如下方式编码:
控制名称和值将被转义.空格字符由+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH' 替换,百分号和两个十六进制数字表示字符的ASCII代码.换行符表示为"CR LF"对(即,'%0D%0A').
控件名称/值按它们在文档中出现的顺序列出.名称通过=' and name/value pairs are separated from each other by&' 与值分隔.
"
以下示例是如何发送简单的"新用户"表单.
如果我在用户对象中有字段名称,密码,电子邮件等,我就像这样指定它们......
user[firstname]=chris&user[login]=cmccauley&user[company_id]=8&user[email]=&user[surname]=mccauley
Run Code Online (Sandbox Code Playgroud)
然后卷曲会逃脱他们给...
user%5Bfirstname%5D=chris&user%5Blogin%5D=cmccauley&user%5Bcompany_id%5D=8&user%5Bemail%5D=&user%5Bsurname%5D=mccauley
Run Code Online (Sandbox Code Playgroud)
...在发布它们之前就像电线转储中的这个摘录...
POST /users/19 HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.10) Gecko/2009042523 Ubuntu/9.04 (jaunty) Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost:3000/users/19/edit
Cookie: _my_session=048d330143de668e027c8cd52654e8c5
Content-Type: application/x-www-form-urlencoded
Content-Length: 259
user%5Bfirstname%5D=chris&user%5Blogin%5D=cmccauley&user%5Bcompany_id%5D=8&user%5Bemail%5D=&user%5Bsurname%5D=mccauley&user_password=********&user%5Bjob_id%5D=14&user%5Bpassword%5D=dd793a64b74e108fcdc5d809040e24afcc21ad2c&authenticity_token=&id=19&_method=PUT
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5042 次 |
| 最近记录: |