在我的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}产生相同的结果。
对此的任何想法都将非常感激
答案 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