Ruby中的HTTP.post_form,带有自定义标头
我试图使用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