.net corePostおよびGetリクエストメソッド

.net corePostおよびGetリクエストメソッド

 public string Post(string url, string postData = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
        {
    
    
            postData = postData ?? "";
            using (HttpClient client = new HttpClient())
            {
    
    
                if (headers != null)
                {
    
    
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                {
    
    
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
        }
        public string Get(string url, string contentType = null, Dictionary<string, string> headers = null)
        {
    
    
            using (HttpClient client = new HttpClient(new HttpClientHandler() {
    
     UseProxy = false }))
            {
    
    
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
    
    
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = client.GetAsync(url).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

おすすめ

転載: blog.csdn.net/weixin_43474597/article/details/110790998