HTTP发布请求中添加

HTTP发布请求中添加

本文介绍了向Net :: HTTP发布请求中添加`Authorization Bearer`哈希(Ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Net :: HTTP Authorization Bearer 添加到POST请求中?

How can I add Authorization Bearer to a POST request with Net::HTTP?

我只能在文档中找到有关基本身份验证"的帮助.

I can only find help for "basic authentication" in the documentation.

req.basic_auth 'user', 'pass'

来源: https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication

我正在尝试复制如下所示的卷曲:

I'm trying to replicate a curl that would look like:

> curl 'http://localhost:8080/places' -d '{"_json":[{"uuid":"0514b...",
> "name":"Athens"}]}' -X POST -H 'Content-Type: application/json' -H
> 'Authorization: Bearer eyJ0eXAiO...'

目前我要:

require 'net/http'
require 'net/https'
require 'uri'

uri = URI('http://localhost:8080/places')

res = Net::HTTP.post_form(uri, '_json' => [{'uuid': '0514b...', 'name':'Athens'}])

但是我在弄清楚如何添加 Authentication:Bearer ... 部分时遇到了麻烦.

But I'm having trouble figuring out how to add the Authentication: Bearer... part.

有人有经验吗?

推荐答案

我认为您不能使用 post_form 方法添加自定义标头.您可以使用post方法添加它.请尝试以下代码:

I dont think you can add custom headers with the post_form method. You can add it with post method. Try the code below:

uri = URI("http://localhost:8080/places")
params = [{'uuid': '0514b...', 'name':'Athens'}]
headers = {
    'Authorization'=>'Bearer foobar',
    'Content-Type' =>'application/json',
    'Accept'=>'application/json'
}

http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)

这篇关于向Net :: HTTP发布请求中添加`Authorization Bearer`哈希(Ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 01:18