overture8
overture8

Reputation: 119

Can't get httpc basic auth example to work with https

This is my first time using erlang and I decided to try and write a wrapper for an API. Here's what I've got so far:-

            -module(my_api_wrapper).

            %% API exports
            -export([auth/0]).

            auth() ->
                application:start(inets),
                application:start(ssl),
                AuthStr = base64:encode_to_string("username:password"),

                Method = post,
                URL = "https://api.endpoint.com/auth",
                Header = [{"Authorization", "Basic " ++ AuthStr}],
                Type = "application/json",
                Body = "{\"grant_type\":\"client_credentials\"}",
                HTTPOptions = [],
                Options = [],
                httpc:request(Method, {URL, Header, Type, Body}, HTTPOptions, Options).

When testing this at the shell I get an error:-

{error,{failed_connect,[{to_address,{"api.endpoint.com",
                                 443}},
                    {inet,[inet],closed}]}}

I can't figure out what I'm doing wrong here! I'm running this version Erlang/OTP 19 [erts-8.0.2]. Any help appreciated.

Upvotes: 2

Views: 1039

Answers (1)

overture8
overture8

Reputation: 119

For anyone who it might help - here's exactly what I changed to make the code in my original question work - thanks to Dogbert for his comment above.

        -module(my_api_wrapper).

        %% API exports
        -export([auth/0]).

        auth() ->
            application:start(inets),
            application:start(ssl),
            AuthStr = base64:encode_to_string("username:password"),

            Method = post,
            URL = "https://api.endpoint.com/auth",
            Header = [{"Authorization", "Basic " ++ AuthStr}],
            Type = "application/json",
            Body = "{\"grant_type\":\"client_credentials\"}",
            % ADD SSL CONFIG BELOW!
            HTTPOptions = [{ssl,[{versions, ['tlsv1.2']}]}], 
            Options = [],
            httpc:request(Method, {URL, Header, Type, Body}, HTTPOptions, Options).

Upvotes: 2

Related Questions