ruby http请求发布方法

时间:2017-11-21 17:12:22

标签: ruby http post request

我想拿令牌,但我有问题。

我的代码:

require 'uri'
require 'net/http'
url = URI.parse('https://ams.iaau.edu.kg/api/authentication/id/password')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == 'https')
request = Net::HTTP::Post.new(url.path)
response = http.request(request)
puts response.message
puts response.code

我有这样的输出:

Unsupported Media Type
415

API Doc

URL /api/authentication/:id/:password Method POST 
URL Params Required: id=[Integer] password=[String] hashed in sha256 
Data 
  Params None 
  Success Response: Code: 200 OK 
    Content: {"authToken":"eyJhbGciOiJIUzI1NiJ9...", "expires": "2017-10-11T12:13:47.441"} 
  Error Response: Code: 401 Unauthorized 
    Content: {"Status":"Wrong Password"} Code: 401 Unauthorized 
    Content: {"Status":"User doesn't exist"}

1 个答案:

答案 0 :(得分:1)

好了,现在您已发布了一些信息,我将假设这是一个json API,因为响应是json。

更新尝试此操作

require 'uri'
require 'net/http'
uri = URI.parse('https://ams.iaau.edu.kg/api/authentication/id/password')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')
response = http.send_request('POST',uri.request_uri)

我现在正按照预期获得401未经授权,因为我没有身份证或密码

如果您更喜欢原始代码,我找到了直接设置请求内容类型的解决方案,例如。

require 'uri'
require 'net/http'
url = URI.parse('https://ams.iaau.edu.kg/api/authentication/id/password')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == 'https')
request = Net::HTTP::Post.new(url.path)
request.content_type = 'application/json' # HERE
response = http.request(request)