Phoenix / Elixir - cURL有效,但HTTPoison失败了

时间:2017-10-27 19:02:23

标签: curl elixir phoenix-framework httpoison agile-crm

在我的Phoenix应用程序中,我正在尝试使用HTTPoison HTTP客户端(https://hexdocs.pm/httpoison/api-reference.html)向AgileCRM API发出请求。我能够使用cURL成功发出请求,但是我在凤凰城复制它的尝试失败了401 UNAUTHORIZED错误。

我成功的cURL:

$ curl https://domain.agilecrm.com/dev/api/contacts/search/email \
-H "Accept: application/json" \
-d 'email_ids=["contact@test.com"]' \
-u admin@test.com:api_key

返回状态200和请求的数据。

我失败的HTTPoison:

url = "https://domain.agilecrm.com/dev/api/contacts/search/email"
body = Poison.encode!(%{"body": "email_ids=['contact@test.com']"})
headers = [{"Accept", "application/json"}, {"Authorization", "admin@test.com:api_key"}]

response = HTTPoison.post!(url, body, headers)

IO.inspect response

返回

%HTTPoison.Response{body: "<html><head>\n<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<title>401 UNAUTHORIZED</title>\n</head>\n<body text=#000000 bgcolor=#ffffff>\n<h1>Error: UNAUTHORIZED</h1>\n</body></html>\n",
headers: [{"X-TraceUrl", "/appstats/details?time=1509129565372&type=json"},
{"WWW-Authenticate", "Basic realm=\"agilecrm\""},
{"Content-Type", "text/html; charset=utf-8"},
{"X-Cloud-Trace-Context", "8de994n2tbu2o356891bc3e6"},
{"Date", "Fri, 27 Oct 2017 18:39:25 GMT"}, {"Server", "Google Frontend"},
{"Content-Length", "200"}],
request_url: "https://domain.agilecrm.com/dev/api/contacts/search/email", status_code: 401}

从消息中,我假设(可能不正确)问题与授权数据有关。我的理解是,cURL中的-u标志等同于添加Authorization标头,但可能不是?

HTTPoison还允许options参数,其中一个选项(ha!)是&#34;:proxy_auth - 代理身份验证{User,Password} tuple&#34;,但是传递{{1}产生相同的结果。

对此的任何想法都将非常感激

2 个答案:

答案 0 :(得分:4)

相当于curl -u的是basic_auth option of hackney,而不是HTTPoison的proxy_auth。您可以像这样使用它:

HTTPoison.post!(url, body, headers, hackney: [basic_auth: {"admin@test.com", "api_key"}])

答案 1 :(得分:2)

实际上curl -u做得更多,请查看以下答案:What is -u flag on cURL actually doing?

它将您的用户:密码编码为base 64字符串,并添加Basic前缀。

你应该发送这样的标题

Authorization: Basic base64 encoded string