首页 > 解决方案 > 如何从 C# 代码在同一会话中执行两个依赖的 odata url

问题描述

我需要从 C# 代码中调用两个 sap 的 odata URL。第一个 URL 将设置过滤器,第二个 URL(通用 URL)将给出实际响应。

第一个网址:

https://<>/sap/opu/odata/SALM/TM_SERVICE/setFilters?sap-language=EN&filter='2%2Ctime%3D%E2%80%8E4%E2%80%8E%2F%E2%80% 8E1%E2%80%8E%2F%E2%80%8E2019%E2%80%8E%20%E2%80%8E10%E2%80%8E%3A%E2%80%8E31%E2%80%8E% 3A%E2%80%8E24%E2%80%8E%20%E2%80%8EAMc%3ATest%20Suite%20for%20Focused%20Build%2Cw%3A%2CT%3D<>'

第二个网址:

https://<>//sap/opu/odata/SALM/TM_SERVICE/TILECollection(ConfigID='1%20',PageID='2%20',TileID='8%20')?$format=json&sap-语言=EN

第二个 URL 是通用和常量 URL,但在第一次执行具有不同参数值的第一个 URL 后,第二个 URL 将给出不同的响应。

在浏览器中,我可以执行这两个 URL 并查看不同参数值的响应差异。

需要 C# 代码来模拟浏览器行为。在 C# 代码中,第二个 URL 响应是不变的,不会被更改。

尝试使用以下方法:WebRequest、HttpWebRequest、HttpClient、WebClient 以及传递 cookie(从第一个响应收到的 cookie 在执行第二个 url 时传递给 Request)

var httpClientHandler = new HttpClientHandler()
                    {
                        Credentials = credential,
                        CookieContainer = cookieContainer
                    };

                    using (HttpClient client = new HttpClient(httpClientHandler))
                    {
                        using (HttpResponseMessage response = client.GetAsync("<<first url>>").Result)
                        {
                            Uri uri = new Uri(string.Format(ConfigurationManager.AppSettings["TestPlanSetFilters"], s));
                            IEnumerable<Cookie> responseCookies = cookieContainer.GetCookies(uri).Cast<Cookie>();
                            foreach (Cookie cookie in responseCookies)
                            {
                                cookieContainer.Add(cookie);
                            }
                        }

                            using (HttpResponseMessage response1 = client.GetAsync("<<second url>>").Result)
                            {
                                using (HttpContent content1 = response1.Content)
                                {
                                    var json2 = content1.ReadAsStringAsync().Result;
                             }                            
                        }                        

                    }

标签: c#odata

解决方案


推荐阅读