net core后台访问外部web api

 private async Task<string> HttpPost(string url, Dictionary<string, string> parameters, CookieContainer cookieContainer)
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.CookieContainer = cookieContainer;
            HttpClient client = new HttpClient(handler);
            HttpContent content = new FormUrlEncodedContent(parameters);
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();

            // 保存响应中的Cookie信息
            IEnumerable<string> cookieHeaders;
            if (response.Headers.TryGetValues("Set-Cookie", out cookieHeaders))
            {
                foreach (string cookieHeader in cookieHeaders)
                {
                    cookieContainer.SetCookies(new Uri(url), cookieHeader);
                }
            }

            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
        public async Task<string> HttpGet(string url, Dictionary<string, string> parameters, CookieContainer cookieContainer)
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.CookieContainer = cookieContainer;
            HttpClient client = new HttpClient(handler);

            // 构建查询字符串
            string queryString = string.Join("&", parameters.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
            string urlWithQuery = $"{url}?{queryString}";

            HttpResponseMessage response = await client.GetAsync(urlWithQuery);
            response.EnsureSuccessStatusCode();

            // 保存响应中的Cookie信息
            IEnumerable<string> cookieHeaders;
            if (response.Headers.TryGetValues("Set-Cookie", out cookieHeaders))
            {
                foreach (string cookieHeader in cookieHeaders)
                {
                    cookieContainer.SetCookies(new Uri(url), cookieHeader);
                }
            }

            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }




应用:

CookieContainer cookieContainer = new CookieContainer();

// 创建一个新的Cookie对象
Cookie cookie = new Cookie("cookie_name", "cookie_value");
cookie.Domain = "example.com"; // 设置cookie的域名

// 将Cookie对象添加到CookieContainer中
cookieContainer.Add(cookie);

Dictionary<string, string> parameters = new Dictionary<string, string>()
{
    { "key1", "value1" },
    { "key2", "value2" }
};
string url = "https://example.com";
string response = await HttpGet(url, parameters, cookieContainer);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值