【问题标题】:Phoenix/Elixir - cURL works, but HTTPoison failsPhoenix/Elixir - cURL 有效,但 HTTPoison 失败
【发布时间】:2017-10-27 19:02:23
【问题描述】:

在我的 Phoenix 应用程序中,我尝试使用 HTTPoison HTTP 客户端 (https://hexdocs.pm/httpoison/api-reference.html) 向 AgileCRM API 发出发布请求。我能够使用 cURL 发出成功的请求,但我在 Phoenix 中复制它的尝试失败并出现 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 参数,其中一个选项(哈哈!)是“:proxy_auth - 代理身份验证 {User, Password} 元组”,但传递 [proxy_auth: {"admin@test.com", "api_key"}] 会产生相同的结果。

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

【问题讨论】:

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


    【解决方案1】:

    curl -u 的等效项是 basic_auth option of hackney,而不是 HTTPoison 的 proxy_auth。你可以这样使用它:

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

    【讨论】:

    • 完美! Dogbert,你又救了我。
    【解决方案2】:

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

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

    你应该发送这样的标题

    Authorization: Basic base64 encoded string
    

    【讨论】:

    • 谢谢 - 接受的答案对我有用,但这真的很有用(我不知道)。
    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2013-10-23
    • 2020-10-06
    • 2016-12-09
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多