Search code examples
c#postmanmagento2magento-rest-api

Restful API working in postman, C# not Working [Magento Integration]


I am integrating with Magento 2, using RESTful APIs. When I use postman, it works like charm, while in C# code, it returns "Unauthorized 401" exception.

However, It was working in C# code earlier, but suddenly it stopped working.

I have tried every way, I tried (WebRequest, HTTPClient & RESTsharp) the same exception returned.

Also, I am using Fiddler 4 to catch & match the requests, I used Fiddler to C# plugins to extract C# code, also I used the RESTsharp Code of Postman same exception returned.

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

       //Calls request functions sequentially.
        private string MakeRequests()
        {
            HttpWebResponse response;

            if (Request_hatolna_co(out response))
            {
                //Success, possibly uses response.

                string responseText = ReadResponse(response);
                response.Close();
                return responseText;
            }
            else
            {
                //Failure, cannot use response.
                return "";
            }
        }

        private static string ReadResponse(HttpWebResponse response)
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                Stream streamToRead = responseStream;
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    streamToRead = new GZipStream(streamToRead, CompressionMode.Decompress);
                }
                else if (response.ContentEncoding.ToLower().Contains("deflate"))
                {
                    streamToRead = new DeflateStream(streamToRead, CompressionMode.Decompress);
                }

                using (StreamReader streamReader = new StreamReader(streamToRead, Encoding.UTF8))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }


        private bool Request_hatolna_co(out HttpWebResponse response)
        {
            response = null;

            try
            {
                //Create a request to URL.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://MAGENTO.co/index.php/rest//V1/orders/items?searchCriteria[filter_groups][0][filters][0][field]=item_id&searchCriteria[filter_groups][0][filters][0][value]=1");

                //Set request headers.
                request.KeepAlive = true;
                request.Headers.Set(HttpRequestHeader.Authorization, "Bearer xxxxxxxxxxxxxxxxxxxxxx");
                request.Headers.Add("Postman-Token", @"1181fa03-4dda-ae84-fd31-9d6fbd035614");
                request.Headers.Set(HttpRequestHeader.CacheControl, "no-cache");
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36";
                request.ContentType = "application/json";
                request.Accept = "*/*";
                request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9,ar;q=0.8,la;q=0.7");
                request.Headers.Set(HttpRequestHeader.Cookie, @"store=default; private_content_version=f16533d4f181d42a1b3f386fa6d2cdf1");

                //Get response to request.
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                //ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found)
                if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
                else return false;
            }
            catch (Exception)
            {
                if (response != null) response.Close();
                return false;
            }

            return true;
        }

Solution

  • The problem was in the URL, where Magento's (Server's) Admin Changed it to [HTTPS] instead of [HTTP].

    That concludes the difference between [Postman, Insomnia, or any other API app] & the C# code, that C# doesn't handle the [HTTP vs HTTPs], while the API app can handle it.