【发布时间】:2013-05-29 01:41:48
【问题描述】:
我正在尝试从我的代码中调用 Paypal api。我设置了沙盒帐户,当我使用 curl 时它可以工作,但我的代码工作方式不同,而是返回 401 Unauthorized。
这里的 curl 命令是 documented by Paypal
curl https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "A****:E****" -d "grant_type=client_credentials"
更新:显然.Credentials 并不能解决问题,而是手动设置Authorization 标头(参见代码)
这是代码(精简到其本质):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language:en_US")
// this doesn't work:
**request.Credentials = new NetworkCredential("A****", "E****");**
// DO THIS INSTEAD
**string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));**
**request.Headers["Authorization"] = "Basic " + authInfo;**
using (StreamWriter swt = new StreamWriter(request.GetRequestStream()))
{
swt.Write("grant_type=client_credentials");
}
request.BeginGetResponse((r) =>
{
try
{
HttpWebResponse response = request.EndGetResponse(r) as HttpWebResponse; // Exception here
....
} catch (Exception x) { .... } // log the exception - 401 Unauthorized
}, null);
这是Fiddler(原始)捕获的代码的请求,由于某种原因没有授权参数:
POST https://api.sandbox.paypal.com/v1/oauth2/token HTTP/1.1
Accept: application/json
Accept-Language: en_US
Host: api.sandbox.paypal.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials
【问题讨论】:
-
接受标头中缺少一个空格,但我看不到任何其他明显的内容。您是否尝试过捕获这两个请求以查看有什么不同,例如使用wireshark或Fiddler等代理?
-
@Rup 我尝试使用 Fiddler,仍然无法捕获 curl 请求,但代码请求不包含 Auth 标头(请参阅更新)
-
是的,一些 HTTP 库,例如除非远程服务器要求,否则 Apache 不会发送凭据,但我不知道 .NET 也会发送凭据。或者至少它应该与他们一起回复 401。可能有办法在请求对象上强制它?
-
有一个令人不快的解决方法in this old answer:构建您自己的基本身份验证标头。或者我在想HttpWebRequest.PreAuthenticate。
-
@Rup 是的,我发现并解决了这个问题。感谢您调查它