Ruby HTTPClient check if cookie was sent - ruby

I am getting a "400 Invalid request method." for the GET request below.
Could that be because I somehow set the cookie (that is demanded by the server) wrong? How can I check that?
What else could it be? (This is for OpenX)
url = URI.parse("https://some.domain/path")
cookie = WebAgent::Cookie.new
cookie.name = "some_token"
cookie.value = "some_value"
cookie.url = url
clnt = HTTPClient.new
clnt.cookie_manager.add(cookie)
clnt.get(url)

The error is in the last line: it should say clnt.put(url) there.

Related

Got the error File type is not supported when uploading a file in ruby on rails

url = URI("https://api.podium.com/v4/messages/attachment")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "multipart/form-data"
request["Authorization"] = "Bearer #{access_token}"
form_data = [["attachment",File.open('D:\proj\v5\ap\fl\Screenshot (1).png')],['data', "#{request_data}"]]
request.set_form(form_data, 'multipart/form-data')
response = https.request(request)
response_body = JSON.parse(response.body)
if response.code == '200' || response.code == '201'
return response_body,'success'
else
return response_body,"#{response.message}"
end
rescue Exception => ex
return ex,'Exception'
end
**
When i am sending the request i got the error like
{"code"=>"invalid_request_values", "message"=>"File type is not supported.", "moreInfo"=>"https://docs.podium.com/docs/errors#invalid_request_values"}
**
Here are a couple of things you could try:
The podium documentation says that the images cannot be above 5mb in size. You can verify if this is the case.
https://help.podium.com/hc/en-us/articles/360039896873-Sending-Messages#Attach%20media%20to%20a%20message
I noticed the code snippet you've shared does set have this line as mentioned in their documentation here https://docs.podium.com/reference/messagesend_with_attachment
request["accept"] = 'application/json'
Maybe adding this header might fix it for you, as you are saying that it is working for you in Postman but not in Ruby.
Try uploading the file from the API Doc reference page itself and check out the code sample they provide there. There are some differences in the code sample you've shared, and the one that podium shows in their doc.

Chilkat2-Python - HTTP Form Authentication problem

Trying to convert from python request to chilkat2.HttpRequest :
import requests
data = {"username": "user","password": "pass","remember": "on"}
sign_in_url = 'https://www.tradingview.com/accounts/signin/'
signin_headers = {'Referer': 'https://www.tradingview.com'}
response = requests.post(url=sign_in_url, data=data, headers=signin_headers)
token = response.json()['user']['auth_token']
P.S. Cause no right username and password - will return status_code:200
b'{"error":"Invalid username or password","code":"invalid_credentials"}'
I have this:
http = chilkat2.Http()
req = chilkat2.HttpRequest()
req.AddParam("username","user")
req.AddParam("password","pass")
req.AddParam("remember","on")
req.Path = '/accounts/signin/'
req.HttpVerb = "POST"
http.FollowRedirects = True
http.SendCookies = True
http.SaveCookies = True
http.CookieDir = "memory"
resp = http.SynchronousRequest('www.tradingview.com',443,True,req)
print(http.LastErrorText)
But response - statusCode: 403 Forbidden
What am I doing wrong?
See the tradingview.com API documentation: https://www.tradingview.com/rest-api-spec/#section/Authentication
You can see that an application/x-www-form-urlencoded POST is required.
It's easy to do with Chilkat. See this documentation showing how to send common HTTP request types: https://www.chilkatsoft.com/http_tutorial.asp
You'll want to send a request like this: https://www.chilkatsoft.com/http_post_url_encoded.asp

Heroku CI Integration

As I attempt to run the Heroku CI tests, I find that I get a
<404> request when I use the request to peek into my webserver's url:
resp = requests.post((url),
json=dict(username = xxx, password = xxx),
)
I've verified that all the url and inputted password and usernames are correct. The url is the predictable pattern from my app's settings. What else could be causing me to get a 404 error?
Are you sure you need to submit user authentication as a JSON payload?
If not, try to use Basic Auth:
username = 'xxx'
password = 'xxx'
resp = requests.post(url, auth=(username, password))

Ruby putting token key in requests

I dont know how to put my key into my requests so they are sent back as
{"status"=>"400", "message"=>"Token parameter is required."}
This is the code I have been using
require 'net/http'
require 'json'
token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
uri = URI(url)
response = Net::HTTP.get(uri)
response.authorization = token
puts JSON.parse(response)
I have tried a couple different things I've found on the internet but all of them just give errors for
undefined method `methodname' for #<String:0x00007fd97519abd0>
According to the API documentation (based on the URL you referenced), you need to provide the token in a header named token.
So, you should probably try some variation of the below (code untested):
token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
uri = URI(url)
request = Net::HTTP::Get.new(uri)
request['token'] = token
response = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(request)
end
More information about Net:HTTP headers can be found in this StackOverflow answer.
As a side note, if you are not locked on using Net::HTTP, consider switching to a friendlier HTTP client, perhaps HTTParty. Then, the complete code looks like this:
require 'httparty'
token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
response = HTTParty.get url, headers: { token: token }
puts response.body

Ruby GET NET HTTP request does not work with AUTHORIZATION and ACCEPT when passed in a header

I've been using the code below to call a third party API . This code works fine (i've changed the url and the credentials but the structure of the code is the same) :
require 'base64'
require 'httparty'
require 'json'
######################################################################
# Get the token first
######################################################################
consumer_key = "my_key"
consumer_secret = "my_secret"
credentials = Base64.encode64("#{consumer_key}:#{consumer_secret}").gsub("\n", '')
url = "https://mysite/token"
body = "grant_type=client_credentials"
headers = {
"Authorization" => "Basic #{credentials}",
"Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8"
}
r = HTTParty.post(url, body: body, headers: headers)
bearer_token = JSON.parse(r.body)['access_token']
######################################################################
# Use the token in a call as authorisation header
######################################################################
api_url = "https://apisite/the_value_i_am_looking_for_in_the_api"
url = URI.parse(api_url)
req = Net::HTTP.new(url.host, url.port)
req.use_ssl = true
# If we are just passing a key that doesn't need to be in the token format
headers = {
'Authorization' => "Bearer #{bearer_token}"
}
# Get the response back (he data is in the response body: resp.body )
resp = req.get(url, headers)
My issue is that the API providers have changed their API so you now need to pass an "accept" into the call via the header. I used POSTMAN to make the call, added the accept to the header and was able to get it working without issue. So far so good.
I then changed my ruby code to extend the headers section to include the accept, using the code below:
headers = {
'Authorization' => "Bearer #{bearer_token}",
'Accept' => 'application/vnd.bluebadge-api.v1+json'
}
I've not added an accept to a header before so I may have gotten the syntax wrong.
However, this returns an unauthorised 401 response code:
#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>
I thought I might have the credentials wrong so remove the accept, try again and this changes to a 406 response code:
#<Net::HTTPNotAcceptable 406 Not Acceptable readbody=true>
If I examine the response I get the message I would expect that the accept header is not the supported version. So I know the credentials are correct (and the fact they match the postman credentials which works):
"{\"apiVersion\": \"1\",\"context\": null,\"id\": null,\"method\": null,\"error\": {\"code\": null,\"message\": null,\"reason\": \"Accept header version is not a currently supported version.\",\"errors\": null}}\n"
So I know all my credentials are correct because I've copied them into the postman request which works with no errors. The value for the accept header is correct because I copied that from a working postman request too.
I am at a loss for why this wouldn't work.
I've looked through the NET HTTP library and cant find anything to help me there. I've seen a couple of posts elsewhere which I've tried and they haven't worked either.
I appreciate any help in trying to solve this.
Found the problem. I was using the credentials from the production environment to get the token then trying to query the test environment API. In my defence they look very similar (only 3 characters different). I think I had a case of the code blindness.
The code I posted does work when I put the correct URL for the environments.
I also found that I could use this:
uri = URI.parse("https://myapi/some_text")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request["Authorization"] = "Bearer #{bearer_token}"
request["Accept"] = "application/vnd.bluebadge-api.v1+json"
response = http.request(request)
Or using HTTParty like this:
response = HTTParty.get('https://myapi/some_text', {
headers: {"Authorization" => "Bearer #{bearer_token}", "Accept" => "application/vnd.bluebadge-api.v1+json" }
})
I would prefer the format of my orginal code or the HTTparty code because it is easy to see from the code that you're passing headers. Hopefully this will help others to double check their authorization credentials...

Resources