Skip to Content
0
Sep 24 at 07:42 PM

(401) Unauthorized - when I tried to perform GET request via SAPB1 Service Layer (.NET)

72 Views

Hi,

I am trying to perform such GET request

https://10.0.1.2:50000/b1s/v1/BusinessPartners?$filter=Phone1 eq '555-0123'&$select=CardCode,Fax,CardName,Phone1

It perfectly works in PostMan

But when I try to do same in c# I get (401) Unauthorized error

Here Is my code for getting SESSION ID

string data = "{ \"CompanyDB\": \"" + _xmlKeysDictionary[_companyDb].ToString() + "\", \"UserName\": \"" + _sbConnectionOptions.ConnUser.ToString() + "\", \"Password\": \"" + _sbConnectionOptions.ConnPassword.ToString() + "\"}";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(_xmlKeysDictionary[URL].ToString() + "/Login");

httpWebRequest.ContentType = "application/json";

httpWebRequest.Method = "POST";

httpWebRequest.KeepAlive = true;

httpWebRequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

httpWebRequest.Headers.Add("B1S-WCFCompatible", "true");

httpWebRequest.Headers.Add("B1S-MetadataWithoutSession", "true");

httpWebRequest.Accept = "*/*";

httpWebRequest.ServicePoint.Expect100Continue = false;

httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");

httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

{ streamWriter.Write(data); }

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

dynamic obj = null;

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))

{

var result2 = streamReader.ReadToEnd();

Console.WriteLine(result);

obj = JsonConvert.DeserializeObject(result2);

if(obj.SessionId.Value != null)

{

sessionID = obj.SessionId.Value.ToString();

}

}

After I get Session ID I added it to client object for bearer

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", sessionID );

After that I perform GET request and get 401 error

image.png

What should I change in code ?

Thanks in advance

Attachments

image.png (57.8 kB)