我正在尝试使用 Nets/HTTP 来使用POST
和放入自定义用户代理。我通常使用open-uri
,但它不能做POST
可以吗?
我用
resp, data = Net::HTTP.post_form(url, query)
我将如何更改它以放入自定义标头?
编辑我的查询是:
query = {'a'=>'b'}
我正在尝试使用 Nets/HTTP 来使用POST
和放入自定义用户代理。我通常使用open-uri
,但它不能做POST
可以吗?
我用
resp, data = Net::HTTP.post_form(url, query)
我将如何更改它以放入自定义标头?
编辑我的查询是:
query = {'a'=>'b'}
你可以试试这个,例如:
http = Net::HTTP.new('domain.com', 80)
path = '/url'
data = 'form=data&more=values'
headers = {
'Cookie' => cookie,
'Content-Type' => 'application/x-www-form-urlencoded'
}
resp, data = http.post(path, data, headers)
你不能post_form
这样做,但你可以这样做:
uri = URI(url)
req = Net::HTTP::Post.new(uri.path)
req.set_form_data(query)
req['User-Agent'] = 'Some user agent'
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
case res
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
else
res.value
end
(阅读net/http 文档了解更多信息)
我需要将 json 发布到具有自定义标头的服务器。我查看的其他解决方案对我不起作用。这是我的解决方案。
uri = URI.parse("http://sample.website.com/api/auth")
params = {'email' => 'someemail@email.com'}
headers = {
'Authorization'=>'foobar',
'Date'=>'Thu, 28 Apr 2016 15:55:01 MDT',
'Content-Type' =>'application/json',
'Accept'=>'application/json'}
http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)
output = response.body
puts output
感谢 Mike Ebert 的 tumblr: http: //mikeebert.tumblr.com/post/56891815151/posting-json-with-nethttp
require "net/http"
uri = URI.parse('https://your_url.com')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ca_path='/etc/pki/tls/certs/'
http.ca_file='/etc/pki/tls/certs/YOUR_CERT_CHAIN_FILE'
http.cert = OpenSSL::X509::Certificate.new(File.read("YOUR_CERT)_FILE"))
http.key = OpenSSL::PKey::RSA.new(File.read("YOUR_KEY_FILE"))
#SSLv3 is cracked, and often not allowed
http.ssl_version = :TLSv1_2
#### This is IMPORTANT
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
#Crete the POST request
request = Net::HTTP::Post.new(uri.request_uri)
request.add_field 'X_REMOTE_USER', 'soap_remote_user'
request.add_field 'Accept', '*'
request.add_field 'SOAPAction', 'soap_action'
request.body = request_payload
#Get Response
response = http.request(request)
#Review Response
puts response.body