Hi All,
I am trying to send the data as json to external api and for that I am trying to set credentials on header but getting 401 error as response uaing below code
httpHeader.Add("Authorization: API Key keyname keyvalue") also attached the postman image keyname and key value are set to the blacked out values.
Can you please let me know how to fix this?
try { new InteropPermission(InteropKind::ClrInterop).assert(); httpHeader = new System.Net.WebHeaderCollection(); request = System.Net.WebRequest::Create(_url); utf8 = System.Text.Encoding::get_UTF8(); bytes = utf8.GetBytes(_json); request.set_Method(_method); httpHeader.Add("Authorization: API Key keyname keyvalue"); request.set_Headers(httpHeader); request.ContentType = 'application/json'; request.set_ContentLength(bytes.get_Length()); requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.get_Length()); response = request.GetResponse(); responseStream = response.GetResponseStream(); streamReader = new System.IO.StreamReader(responseStream); responseJson = streamReader.ReadToEnd(); info(responseJson); } catch (Exception::CLRError) { ex = CLRInterop::getLastException().GetBaseException(); error(ex.get_Message()); } requestStream.Close(); streamReader.Close(); responseStream.Close(); response.Close()
Thanks
I'm sorry, but I know nothing about the API you're using, so I can't tell you how you need to communicate with it. If you know that it's using some standard mechanism for specifying API keys, share the information with us.
If you don't know or it's using a custom solution, consult documentation of the API or contact the provider.
Do we need to send all these details to header too?
Hi Martin,
I need to know how to set the credentials, I have the json that I need to send but I am getting authentication error 401.
What you should send depends on what the web service expects, which we don't know.
By the way, just for inspiration, let me show you a few things that can simplify your code:
using System.IO; using new System.Net; System.Exception ex; try { request = WebRequest::Create(_url); request.set_Method(_method); httpHeader = new WebHeaderCollection(); httpHeader.Add("Authorization: API Key keyname keyvalue"); request.Headers = httpHeader; request.ContentType = 'application/json'; utf8 = System.Text.Encoding::get_UTF8(); bytes = utf8.GetBytes(_json); request.ContentLength = bytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(responseStream); { responseJson = streamReader.ReadToEnd(); } } } } info(responseJson); } catch (ex) { error(ex.Message); }
André Arnaud de Cal...
292,074
Super User 2025 Season 1
Martin Dráb
230,900
Most Valuable Professional
nmaenpaa
101,156