I am trying to retrieve an order from the Eventbrite API. I have a valid OAuth token and order number. I have verified this by using postman which successfully returns the correct JSON.
However when I make the call using the following c# code, I get a 401 Unauthorised:
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Get, "https://www.eventbriteapi.com/v3/orders/{orderNo}");
req.Headers.Add("Authorization", "Bearer {authToken}");
var response = await client.SendAsync(req);
I've tried replacing the header with:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("{authToken}");
I have also tried:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.eventbriteapi.com/v3/orders/{orderNo}");
request.Headers.Add("Authorization", "Bearer {authToken}");
request.Accept = "application/json";
using(WebResponse response = request.GetResponse())
{
using(Stream dataStream = response.GetResponseStream())
{
using(StreamReader reader = new StreamReader(dataStream))
{
string responseFromServer = reader.ReadToEnd();
}
}
}
All of these get a 401 response.
I know the authtoken and the eventid are correct, so there must be something wrong with my code.
Am I doing something wrong with the authroisation token?
Have you tried ?token={authToken} option on the EventBrite API?
This would at least confirm if it's a problem with the way the header is being sent across.
http://developer.eventbrite.com/docs/auth/
You omitted the trailing '/' in the URL, which caused a subsequent redirect from "eventbriteapi.com/v3/orders/{orderNo}" to "eventbriteapi.com/v3/orders/{orderNo}/". The authorization header was dropped in the redirect.
Related
Trying to call WebServices from C# and getting below error:
System.Net.WebException: 'The remote server returned an error: (502) Bad Gateway
Code:
WebRequest request = WebRequest.Create("https://xxxxx/cgi/webservice.pl?function=get_latest_ts_values&site_list=130105B&datasource=AT&varfrom=10.00&varto=10.00&lookback=60&format=csv");
request.Method = "GET";
WebResponse response = request.GetResponse();
using (Stream dataStream = response.GetResponseStream() )
{
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
Console.ReadLine();
}
But works fine when i use Postman or just copy url in browser and also works fine with below python code:
import requests
dataload = {}
dataurl = "https://xxxxx/cgi/webservice.pl?function=get_latest_ts_values&site_list=130105B&datasource=AT&varfrom=10.00&varto=10.00&lookback=60"
headers = {}
response = requests.request("GET", dataurl, headers=headers, data=dataload)
for dataresp in response:
print(dataresp)
What am I doing wrong with C# code?
The uri for the WebRequest has the query parameter &format=csv. Maybe this is why you are getting a 502. The Python request is missing that query parameter. Did you try the WebRequest by removing that part?
Could be incorrect content type or user agent having the wrong information. Postman could be setting these values without your knowledge. Might try in the exception seeing if there is a a response stream and read it through a streamreader to see if there is any more information you're not seeing to point you in the correct direction.
Ended up using RestSharp and it works fine. (https://www.nuget.org/packages/RestSharp)
string Uri = "https://xxxx/cgi/webservice.pl?xxxx";
var client = new RestSharp.RestClient(Uri);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I am trying to use an Api to get the value of some metrics with a c# application. My code looks like this:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://myServer/api/measures/component?componentKey=myProject&metricKeys=bugs,new_bugs");
httpWebRequest.Headers.Add("Authorization", token);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string result;
using (var streamreader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamreader.ReadToEnd();
}
var joResponse = JObject.Parse(result);
var measures = (JArray)joResponse["component"]["measures"];
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
When i write the same API into the address box of my browser, i get the result i looked for. And the token for the header is generated by my server. But for some reason I catch an error 401 when trying to get the response for this httpwebrequest in the code. What am I doing wrong?
Alternatively, instead of using a token, I tried using credentials:
httpWebRequest.Credentials = new NetworkCredential(name, password);
The result was the same.
EDIT:
I tried to use the header
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
instead. This also didn't work out.
I had this problem last week and couldn't believe what I've experienced.
In the "Authorization" header you have to encode the token with an empty password like this:
"Authorization", $"Basic {Convert.ToBase64String(Encoding.ASCII.GetBytes(apiKey + ":"))}"
The colon after "apiKey" is very important.
I am developing a C# application which needs to use the onelogin API to retrieve a session token. I am able to authenticate and and create a token with the following code:
WebRequest Authrequest = WebRequest.Create("https://api.us.onelogin.com/auth/oauth2/token");
Authrequest.Method = "POST";
Authrequest.ContentType = "application/json";
Authrequest.Headers.Add("cache-control", "no-cache");
Authrequest.Headers.Add("Authorization: client_id:XXXXXXX7bbf2c50200d8175206f664dc28ffd3ec66eef0bfedb68c3366420dc, client_secret:XXXXXXXXXX6ba2802187feb23f6450c6812b8e6639361d24aa83f12010f ");
using (var streamWriter = new StreamWriter(Authrequest.GetRequestStream()))
{
string Authjson = new JavaScriptSerializer().Serialize(new
{
grant_type = "client_credentials"
});
streamWriter.Write(Authjson);
}
WebResponse AuthReponse;
AuthReponse = Authrequest.GetResponse();
Stream receiveStream = AuthReponse.GetResponseStream ();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream);
JObject incdata = JObject.Parse(readStream.ReadToEnd());
string sToken = incdata["data"][0]["access_token"].Value<string>();
AuthReponse.Close();
However, when running the Create Session Login Token with the following code, it only returns a 400 error, and the message has no detail. Just Bad Request:
//Get the session token for the specified user, using the token recieved from previous web request
WebRequest request = WebRequest.Create("https://api.us.onelogin.com/api/1/login/auth");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("authorization", "bearer:" + sToken);
using (var streamWriter2 = new StreamWriter(request.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(new
{
username_or_email = sUsername,
password = sPassword,
subdomain = "comp-alt-dev"
});
streamWriter2.Write(json);
}
WebResponse response;
response = request.GetResponse();
string streamText = "";
var responseStream = response.GetResponseStream();
using (responseStream)
{
var streamReader = new StreamReader(responseStream);
using (streamReader)
{
streamText = streamReader.ReadToEnd();
streamReader.Close();
//
}
responseStream.Close();
}
Any ideas?
-Thank you
Also for anyone who may be getting this error. in C# the email is case sensitive. I tried User.email.com. In onelogin it was saved as user#email.com. changing the c# to lower case fixed it.
Can you let us know what payload you're sending across the wire to the .../1/login/auth endpoint as well as the response (either as others have suggested as packet snoop, or just as a debug output from the code)
400 means either bad json or the endpoint requires MFA, so this will narrow it down.
~thanks!
Just joining the troubleshooting effort =) -- I can replicate a 400 Bad Request status code with a "bad request" message when the request body contains a username_or_email and/or subdomain value that does not exist, or if the request body is empty.
Can you post what goes over the wire to the OneLogin endpoint...
OK Thanks. So it appears your subdomain does not exist. If you give me an email in the account I can find the correct subdomain value for you.
When trying to get data from a Hitbox API I get a strange result. For a one API's command it happens everytime, for the other only sometimes. The result more or less like that (this is the last result I have got):
\u001f�\b\0\0\0\0\0\0\u0003콋w�8������s�Μmu�~��s��N�t&��N�g6��C��Ͷ$z%9igf��[(�\u0005�\u000f��(:�6����\u000f\b P�C\u0015\n�\u007f�V�\u007f�d��h����2_�&��Nj,�����S������q�\u0017�7��\u0019<�n�~��YoVY�\u0018M>�S�kP���|^���w������9�w2��\u0605�4�Ƿ�&\u0015�ƛ��Xo�\u0014[�6w\u0011onVP\u0005��e\u000e��\u05ca�l�/����⇝��%�u�u�s�����=���k�w��z\u0003�a����SR,���s�1����ůdž��2~.6\u0006T>��fR��l�(���\u0017�GHoV�&/�m#�'\u0013�C�N/��E|Q�\u0012���3+�6\u0003z\u0012���q>�{�_��eW�7\u0016�rsIw\u0012\u0018&\u0017��V�\u000f�Ŀ\u001f������e�\u0002A��Zg��U\u0006��\\g\u0015�VP��u.E8Hj�LA���/͋��|�����;xk\u001e��ǣZ�\3y��\u00019\u0017���ī\u0002��ڜ���u����O]v���XA�{�\u0004�K�l.o\u0016�%t\u0006�<{̆O��=�\u0017\u0017\u0015%$G��\"Oϡ�\u007f����^̹hH���q�8�\u0001�6�\u0015�y�{��S��4+�pb-\\eI�bB]^\u001f��{��jՊx�\u0004��\u0001�º��QD��\u001eK\u0001;�\u0002+��Y���!�\a��\u001a��(()>e��ש�r0T?��\u001f�Q���5t�R���� \u0005\u001f(���l\u0013�\v�\r-�\n�U?߭_��&�l>�\r0(N4))/���uc��3�\<�U\u0013\u001f\u0002ȱ���^n6ד��g�/�ʹ��ͧ��rP����\u001f���\f4y~\u0005=�V3�\u001c;�k\u0002}�'�m\u001cc�oG��_\u0003b�4�`��
It's much much longer but it's pointless to copy all of it (about 30000 characters).
My code that I use to get the json result is:
string result;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(hitboxApiLink);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(requestString).Result;
result = response.Content.ReadAsStringAsync().Result;
}
return result;
I used this before:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(Path.Combine(hitboxApiLink, requestString));
request.KeepAlive = false;
request.ContentType = "application/json; charset=utf-8";
WebResponse response = request.GetResponse();
using(StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
}
And it returns the same. But when I try to get data with Google Chrome or Internet Explorer it returns normal result. The api is: http://developers.hitbox.tv/
The link I try to get data from is: https://api.hitbox.tv/media/live/list
The response is GZIPped (even though this wasn't specified by an Accept-Encoding header in the request, so is technically a fault on the server).
Your second example can be fixed by adding the following line before you fire off the request:
request.AutomaticDecompression = DecompressionMethods.GZip;
This should give you everything you need to figure out how to decompress the response of the HttpClient version.
I am not getting the results that documentation says. I login the Buddy; created application; copy this URL and assign to url string; when I execute the program I am not getting results that are expected (status + Accesstoken) as documentation says. Can anyone please tell me if I am missing something as newbie to http calls. Its running on http requester but not on Poster firefox add-on!
Documentation
http://dev.buddyplatform.com/Home/Docs/Getting%20Started%20-%20REST/HTTP?
Code
string parameters = "{appid:'xxxxxx', appkey: 'xxxxxxx', platform: 'REST Client'}";
private async void SimpleRequest()
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse) await request.GetResponseAsync();
}
catch (Exception)
{ }
}
Using the HTTP requester add-on on Firefox, I successfully retrieved an access token so their API work.
In C# they provide a line of code to submit your appid and appkey, that might be the problem :
Buddy.Init("yourAppId", "yourAppKey");
My guess is you have to use their .NET SDK!
You can certainly use the REST API from raw REST the way you're doing, though the .NET SDK will handle some of the more complex details of changing service root. I ran your code using my own Buddy credentials and I was able to get JSON containing an Access Token back. You may need to read the response stream back as JSON to retrieve the access token. I used the following code to dump the JSON to the console:
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
Console.WriteLine(await new StreamReader(response.GetResponseStream()).ReadToEndAsync());
Using Newtonsoft.Json I can parse out my accessToken like this:
Uri url = new Uri("https://api.buddyplatform.com/devices");
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
var parsed = JsonConvert.DeserializeObject<IDictionary<string,object>>( (await new StreamReader(response.GetResponseStream()).ReadToEndAsync()));
var accessToken = (parsed["result"] as JObject).GetValue("accessToken").ToString();
Console.WriteLine(accessToken);
The 3.0 SDK does all of this for you while exposing the rest of the service through a thin REST wrapper, the migration guide for the 3.0 SDK should help with this.