5

我正在尝试让您第一次致电 Paypal,其中帖子消息处于卷曲状态。我想将它们转换为 C#。但我无法编辑Accept标题。

curl https://api.sandbox.paypal.com/v1/oauth2/token \
 -H "Accept: application/json" \
 -H "Accept-Language: en_US" \
 -u "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp" \
 -d "grant_type=client_credentials"

我的代码是

string url = "https://api.sandbox.paypal.com/v1/oauth2/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);            

//request.ContentType = "Content-type: text/xml";
//Client.Headers.Add(HttpRequestHeader.UserAgent, "user agent to send");
//request.Headers.Add(HttpRequestHeader.Accept, "application/json");
//request.Headers.Add(HttpRequestHeader.Referer, "string");
//request.Headers.Add(HttpRequestHeader.AcceptLanguage, "string");

request.Method = "POST";
string authInfo = "AfKNLhCngYfGb-Eyv5gn0MnzCDBHD7T9OD7PATaJWQzP3I1xDRV1mMK1i3WO:ECSAgxAiBE00pq-SY9YB5tHw0fd2UlayHGfMr5fjAaULMD2NFP1syLY7GCzt";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
//request.Headers["Accept"] = "application/json";
request.Headers["Accept-Language"] = "en_US";
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("grant_type=client_credentials");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

我收到内部服务器错误 500。但它适用于 curl。我怎样才能在 C# 中做到这一点?

4

1 回答 1

5

我以前用来提供这样的命名值的UploadValues一种方法是使用WebClient. 这完美地复制了您在 curl 中找到的功能(出于相同目的,我已将其用于与 Instagram API 集成)。

这是一个小示例代码来说明:

string authInfo = "AfKNLhCngYfGb-Eyv5gn0MnzCDBHD7T9OD7PATaJWQzP3I1xDRV1mMK1i3WO:ECSAgxAiBE00pq-SY9YB5tHw0fd2UlayHGfMr5fjAaULMD2NFP1syLY7GCzt";
WebClient client = new WebClient();
NameValueCollection values;

values = new NameValueCollection();
values.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo)));
values.Add("Accept", "application/json");
values.Add("Accept-Language", "en_US");

client.UploadValues("https://api.sandbox.paypal.com/v1/oauth2/token", values);

这可能无法开箱即用(正如我在上面所阐述的那样),但希望能带您朝着正确的方向前进。

于 2013-08-02T11:09:39.170 回答