How to sent a request by HTTP using relative url?

146 views Asked by At

There's a HTTP Message like:

POST /v1.0/oauth2/accessToken HTTP/1.1
Host:api.dingtalk.com
Content-Type:application/json

{
    ...
}

If I want to send it by HTTP.post function, I should let url = "https://api.dingtalk.com/v1.0/oauth2/accessToken".
Could I use relative url url = "/v1.0/oauth2/accessToken", and write "host" => "api.dingtalk.com" in headers?
I know this is wrong way, I'm wondering how to separate them in two parts while using HTTP.request()?

I Tried:

url = "/v1.0/oauth2/accessToken"
headers = Dict([(
    "host" => "api.dingtalk.com",
    "Content-Type" => "application/json"
)])
body = Dict([
    ...
])
r = HTTP.post(url, headers, body)

get:

ERROR: ArgumentError: missing or unsupported scheme in URL (expected http(s) or ws(s)): v1.0/oauth2/accessToken

obviously it doesn't work.

1

There are 1 answers

2
Raghav Kukreti On

With HTTP.request(), you can also use a relative URL and a Dict object for the headers as you've attempted, but you need to provide the full URL (including the protocol) as the base_uri argument, like this:

using HTTP
using JSON

base_uri = "https://api.dingtalk.com"
url = "/v1.0/oauth2/accessToken"'
full_url = base_uri * endpoint
headers = Dict([
    "host" => "api.dingtalk.com",
    "Content-Type" => "application/json"
])
body = Dict([
    # your request body here
])
response = HTTP.request("POST", full_url, headers, JSON.json(body))

Hope this helps!