关于使用ruby代码的http POST api调用的问题

时间:2018-01-30 07:04:36

标签: ruby-on-rails ruby api net-http

我将访问Riskscreen api来验证用户身份。为了测试api,我编写了一个ruby代码片段来进行示例POST调用,以获取Riskscreen api中的令牌数。

我的代码是:

public someMethod( @WebParam(name="xyz" ... )

但是我收到以下错误:

class Grid
{
    ...
    void placeBoat(int, int, int, int);
    ...
};

void Grid::placeBoat(int iX1, int iY1, int iX2, int iY2)
{
    ...
}

如果我将标题行更改为

client_name

然后我收到了这个错误:

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($draftUrl);
$templateProcessor->setValue("client_name", $clientName);

$filename = '30.docx';
$templateProcessor->saveAs($filename);

坚持这一段时间。请帮我理清一下。

2 个答案:

答案 0 :(得分:2)

标题的键必须是String而不是Symbol

header = {'api-key' => 'my api key','Content-Type' => 'application/json', 'Accept' => 'application/json'}

另一个问题是net/http自动为大写标题,api-key - > Api-Key导致您的服务器上出现Authorization Error。一种解决方案是创建新类来包装api-key以防止Ruby执行该操作

class HeaderCaseSensitive < String
  def capitalize
    self
  end

  def split(*args)
    super.each do |str|
      HeaderCaseSensitive.new(str)
    end
  end

  def to_s
    self
  end
end

然后更改标题:

header = {HeaderCaseSensitive.new('api-key') => 'xxxx','Content-Type' => 'application/json', 'Accept' => 'application/json'}

总而言之,以下代码将起作用:

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

class HeaderCaseSensitive < String
  def capitalize
    self
  end

  def split(*args)
    super.each do |str|
      HeaderCaseSensitive.new(str)
    end
  end

  def to_s
    self
  end
end

@toSend = {}.to_json

uri = URI.parse("https://api.riskscreen.com/api/v1/user/tokens")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
header = {HeaderCaseSensitive.new('api-key') => 'xxx','Content-Type' => 'application/json', 'Accept' => 'application/json'}
https.set_debug_output($stdout)
req = Net::HTTP::Post.new(uri.path, header)
req.body = "[ #{@toSend} ]"


res = https.request(req)


puts "------------"
puts "Response #{res.code} #{res.message}: #{res.body}"

答案 1 :(得分:1)

您可以尝试删除:

req.body = "[ #{@toSend} ]"

并替换为:

req.set_form_data({})
# or 
req.body = "{}"

抱歉,我不确定。