在C#中使用授权进行HTTP发布

时间:2013-08-02 10:58:23

标签: c# curl

我正在尝试Make your first call Paypal帖子邮件处于curl状态。我想将它们转换为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.但它适用于卷曲。我怎么能在C#中做到这一点?

1 个答案:

答案 0 :(得分:5)

我之前使用过一种方法来提供这样的命名值,就是使用UploadValues的{​​{1}}方法。这完美地复制了你在curl中找到的功能(为了同样的目的,我使用它与Instagram API集成)。

这里有一些示例代码来说明:

WebClient

这可能无法开箱即用(正如我上面所述),但希望能让你朝着正确的方向前进。