使用HTTP标头发送POST请求

时间:2014-01-10 16:29:47

标签: ruby api rest

这是一个很新的东西,在Ruby中学习API。使用Emails服务的API在系统中创建用户。

这是POST的一个例子:

POST http://localhost:8080/core/postgres-pages-xy/api/rest/v4/user/create?email=user003@test.invalid HTTP/1.1
Authorization: Basic bWFzdGVyQGVuubXVjLmVjaXJjbGUuZGU6aDhuc3d1cnN0
User-Agent: curl/7.29.0
Host: localhost:8080
Proxy-Connection: Keep-Alive
Content-Type:application/json
Accept:application/json
Content-Length: 86

[{"name":"user.FirstName","value":"Stan"}, {"name":"user.LastName", "value":"Laurel"}]

我想我很亲近(是啊)?在Ruby中希望有人能告诉我如何发送我的身份验证。系统要求登录标题不确定如何操作,将是电子邮件和密码:

    require 'uri'
require 'net/http'

uri = URI("https://site.com/api/rest/v4/user/create?email=ruby1@ruby.com")
https = Net::HTTP.new(uri.host, uri.port)


request = Net::HTTP::Post.new(uri.path)
request.basic_auth 'email', 'pass'

request["user.FirstName"] = 'Liam'
request["user.LastName"] = 'Coates'

response = https.request(request)
puts response

感谢您的反馈或学习。

1 个答案:

答案 0 :(得分:0)

您可以在网址中输入凭据:

url = "http://username:password@localhost:8080/core/postgres-pages-xy/api/rest/v4/user/create"

如果有用户名和密码,则应自动执行HTTP基本身份验证(source)。

然而据说这已被弃用,因此有一个更长的解决方案:

req = Net::HTTP::Post.new(uri)
req.basic_auth 'user', 'pass'

res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req)
}
puts res.body