ruby http request post method

人盡茶涼 提交于 2021-02-10 22:51:05

问题


I want take token,but i have a problems.

My code:

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

I have output like this:

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:


Okay now that you have posted some information I am going to assume this is a json API because the responses are json.

Update Try this instead

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)

I am now getting a 401 Unauthorized as expected since I don't have an id or password

If you would prefer your original code I have found the solution which is setting the content type of the request directly e.g.

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)


来源:https://stackoverflow.com/questions/47418857/ruby-http-request-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!