美文网首页
C# http post请求

C# http post请求

作者: 在凌晨失了眠 | 来源:发表于2021-02-04 11:49 被阅读0次

设置身份验证

        /// <summary>
        /// Http Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="statusCode"></param>
        /// <returns>string响应结果</returns>
        public string PostResponse(string url, string postData, out string statusCode)
        {
            string result = string.Empty;
HttpResponseMessage response ;
            //设置Http的正文
            HttpContent httpContent = new StringContent(postData);
            //设置Http的内容标头
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //设置Http的内容标头的字符
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                string value = $"{user.UserName}:{user.Password}";
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.Default.GetBytes(value)));
                //异步Post
                try
                {
                    response = httpClient.PostAsync(url, httpContent).Result;
                }
                catch (Exception ex)
                {
                    Tips.Text = ex.Message;
                }
                //输出Http响应状态码
                statusCode = response.StatusCode.ToString();
                //确保Http响应成功
                if (response.IsSuccessStatusCode)
                {
                    //异步读取json
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

相关文章

网友评论

      本文标题:C# http post请求

      本文链接:https://www.haomeiwen.com/subject/cotitltx.html