0

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

我成功的卷曲:

$ 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}

从消息中,我假设(可能不正确)问题出在授权数据上。我的理解是-ucURL 中的标志相当于添加Authorization标题,但也许不是?

HTTPoison 还允许一个options参数,其中一个选项(哈哈!)是“:proxy_auth - 代理身份验证 {User, Password} 元组”,但传递[proxy_auth: {"admin@test.com", "api_key"}]会产生相同的结果。

对此的任何想法将不胜感激

4

2 回答 2

5

的等价物curl -u是 的basic_auth选项hackney,而不是 HTTPoison 的proxy_auth。你可以像这样使用它:

HTTPoison.post!(url, body, headers, hackney: [basic_auth: {"admin@test.com", "api_key"}])
于 2017-10-27T22:35:19.443 回答
2

实际上curl -u做得更多,请查看以下答案:cURL 上的 -u 标志实际上在做什么?.

它将您的 user:password 编码为 base 64 字符串并添加Basic前缀。

你应该发送这样的标题

Authorization: Basic base64 encoded string
于 2017-10-27T20:41:19.170 回答