简体   繁体   中英

Rest client post with username and password

curl --request POST \
  --url https://example.com/token/grant \
  --header 'password: password' \
  --header 'username: user' \
  --data '{"app_key":"my_app_key","app_secret":"my_app_secret"}'

I am trying to get an equivalent ruby code for the above curl request with rest client.

I have tried:

auth = 'Basic ' + Base64.encode64( "#{AA['user_name']}:#{AA['password']}" ).chomp
response = RestClient.post'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}, {  'Authorization' => auth , :accept => :json, 'Content-Type': 'application/json' }
response = JSON.parse(response)

It did not work.

2nd try:

RestClient.post 'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}.to_json,  {'username': 'username', 'password': 'password', content_type: 'application/json'}

Also did not work. I have checked username and password is correct.

It showing that username is missing in the header.

Thanks in advance.

As per the description it seems like when running the request using RestClient the header is action is unable to process the header (username since it is the first key in the header hash).

I have executed the below command on a custom code and it worked.

 RestClient.post 'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}.to_json,  {username: 'username', password: 'password', content_type: 'application/json'}

Note: I have just updated the representation of header keys passed in the header hash.

I have tried with Rest client. It did not work. Then I also tried Faraday, Net HTTP nothing works.

Then I have tried with curb . It works.

require 'curb'
request_path= 'https://example.com/token/grant'
payload = {
          app_key: 'app_key',
          app_secret: 'app_secret'
        }
http = Curl.post(request_path, payload.to_json) do |http|
          http.headers['username'] = 'user_name'
          http.headers['password'] = 'password'
          http.headers['Content-Type'] = 'application/json'
        end
JSON.parse(http.body_str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM