Skip to Content
avatar image
Former Member

(401) Unauthorized - when I tried to create a Sales Order via SAPB1 Hana Service Layer (.NET)

Hi Experts!

I got a problem when when I tried to create a Sales Order via Service Layer.

"The remote server returned an error: (401) Unauthorized."

My Environment:

SAP Business One Hana 9.2 PL00

I have got a SessionId and I used a HttpWebRequest to send my request by POST.

I can get a SO by GET. But failed to create one by POST.

Could you please help me to figure out which parts I missed?

I knew Maira shared a wonderful solution:

http://scn.sap.com/community/business-one-sdk/blog/2015/07/15/how-to-consume-service-layer-odata-services-from-net-via-wcf

But we can't use this solution for some reason.

public void TestCreateSO()
        {
            string DeleveryCreateJSON = @"{
            ""CardCode"": ""C20000"",
            ""DocDueDate"": ""2016-08-18"",
            ""DocumentLines"": [
                        {
                                    ""ItemCode"": ""A00001"",
                                    ""Quantity"":""1""
                        },
                        {
                                    ""ItemCode"": ""A00002"",
                                    ""Quantity"":""1""
                        }
            ]
            }";
            string strRequstCmd = "https://XXXX:50000/b1s/v1/Orders";
            Uri cmdUpdate = new Uri(strRequstCmd);
            HttpWebRequest request = WebRequest.Create(cmdUpdate) as HttpWebRequest;
            SendRequest(request, DeleveryCreateJSON, "POST");
        }
public JObject SendRequest(HttpWebRequest request, string ParamBody, string requsetMethod)
        {
            JObject jo = null;
            try
            {
                if (null != request)
                {
                    request.Accept = "application/json;odata=minimalmetadata";
                    request.KeepAlive = true;                               //keep alive
                    request.ServicePoint.Expect100Continue = false;        //content
                    request.AllowAutoRedirect = true;
                    request.ContentType = "application/json;odata=minimalmetadata;charset=utf8";
                    request.Timeout = 10000000;    //number of seconds before considering a request as timeout (consider to change it for batch operations)


                    //This way works to bring additional information with request headers
                    if (false == string.IsNullOrEmpty(strCurrentSessionGUID))// I have already got the seesion ID. I tried to set it to cookie.
                    {
                        string strB1Session = "B1SESSION=" + strCurrentSessionGUID;
                        if (!string.IsNullOrEmpty(strCurrentRouteIDString))
                            strB1Session += "; " + strCurrentRouteIDString;


                        request.Headers.Add("Cookie", strB1Session);
                    }
                    request.Method = requsetMethod;
                    request.Headers.Add("Prefer", "odata.maxpagesize=" + currentDefaultPagingSizing.ToString());
                    
                    if (!string.IsNullOrEmpty(ParamBody)) //I'm trying to set the params
                    {
                        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                        {
                            string json = ParamBody;
                            streamWriter.Write(json);
                            streamWriter.Flush();
                        }
                    }


                    BuildRequestStringContent(request);
                    var response = request.GetResponse() as HttpWebResponse;//Error occurred here!!!
                    Console.WriteLine(response.GetResponseHeader("Content-Type"));
                    Stream stream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(stream);
                    string jsonText = sr.ReadToEnd();
                    jo = JObject.Parse(jsonText);
                    Console.WriteLine(jsonText);
                    
                }
                else
                    throw new Exception("Failed to intercept the sending request");
            }
            catch (WebException wex)
            {
                var response = wex.Response as HttpWebResponse;
                Console.WriteLine(response.GetResponseHeader("Content-Type"));
                Stream stream = response.GetResponseStream();
                StreamReader sr = new StreamReader(stream);
                string html = sr.ReadToEnd();
                Console.WriteLine(html);
                //LogoutServer();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //LogoutServer();
            }
            return jo;
        }

If I failed to express myself clearly, please let me know! I can provide more information.

Thank you very much!

Billy

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

1 Answer

  • Jul 05, 2017 at 10:13 AM

    There was a bug in ealier SL 9.2 versions that in some cases made it loose the SessionID provided.

    If you can't upgrade your B1 istallation, SAP Support could provide up to date SL binaries that might solve the issue.

    Add comment
    10|10000 characters needed characters exceeded