I'm trying to Make your first call Paypal where the post message are in curl. I want to convert them to C#. But I can't edit Accept
header.
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"
My code is
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();
I'm getting internal server error 500. But it works fine with curl. How can I do this in C#?
One method I have used before to supply named values like this is to use the UploadValues
method of a WebClient
. This perfectly replicates the functionality you find in curl (I have used this for integration with the Instagram API for the same purpose).
Here is a little sample code to illustrate:
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);
This may not work out of the box (as I have laid it out above) but will hopefully take you in the right direction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With