C# HttpClient 请求

本文介绍了一种使用C#实现的HTTP请求处理方法,包括GET、POST、PUT等请求方式,并通过Newtonsoft.Json库进行JSON数据的序列化与反序列化。文中详细展示了如何设置请求头、发送请求及处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  引用 Newtonsoft.Json  

        // Post请求
        public string PostResponse(string url,string postData,out string statusCode)
        {
            string result = string.Empty;
            //设置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())
            {
                //异步Post
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                //输出Http响应状态码
                statusCode = response.StatusCode.ToString();
                //确保Http响应成功
                if (response.IsSuccessStatusCode)
                {
                    //异步读取json
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }
        // 泛型:Post请求
        public T PostResponse<T>(string url,string postData) where T:class,new()
        {
            T result = default(T);

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using(HttpClient httpClient=new HttpClient())
            {
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    //Newtonsoft.Json
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json); 
                }
            }
            return result;
        }

 

        // 泛型:Get请求
        public T GetResponse<T>(string url) where T :class,new()
        {
            T result = default(T);

            using (HttpClient httpClient=new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = httpClient.GetAsync(url).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

 

        // Get请求
        public string GetResponse(string url, out string statusCode)
        {
            string result = string.Empty;

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                statusCode = response.StatusCode.ToString();

                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }
        // Put请求
        public string PutResponse(string url, string putData, out string statusCode)
        {
            string result = string.Empty;
            HttpContent httpContent = new StringContent(putData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
                statusCode = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

 

        // 泛型:Put请求
        public T PutResponse<T>(string url, string putData) where T : class, new()
        {
            T result = default(T);
            HttpContent httpContent = new StringContent(putData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using(HttpClient httpClient=new HttpClient())
            {
                HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

 

C#中,如果你想要使用HttpClient发送HTTP请求,并向服务器端附带参数,通常你会通过`Content`对象来构建请求体。以下是添加不同类型参数的基本步骤: 1. **GET 请求** (查询字符串参数): 对于简单的GET请求,参数可以作为URL的一部分。例如: ```csharp var httpClient = new HttpClient(); string url = "https://api.example.com/resource?key=value"; HttpResponseMessage response = await httpClient.GetAsync(url); ``` 2. **POST、PUT 或 DELETE 请求** (JSON或表单数据): - **JSON**: 使用`JsonSerializer`将对象转换为字符串,然后设置`Content-Type`为`application/json`。 ```csharp var json = JsonConvert.SerializeObject(new { param1 = "value1", param2 = "value2" }); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync("https://api.example.com/resource", content); ``` - **表单数据**: 创建`FormDataCollection`,然后设置到`HttpFormUrlEncodedContent`。 ```csharp var formData = new FormDataCollection(); formData.Add("param1", "value1"); formData.Add("param2", "value2"); var content = new FormUrlEncodedContent(formData); var response = await httpClient.PostAsync("https://api.example.com/resource", content); ``` 3. **上传文件**: 如果有文件需要上传,你可以创建`MultipartFormDataContent`。 ```csharp var file = new ByteArrayContent(File.ReadAllBytes("file.jpg")); file.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); // 添加其他表单字段... var form = new MultipartFormDataContent(); form.Add(file, "file"); var response = await httpClient.PostAsync("https://api.example.com/upload", form); ``` 记得处理可能出现的异常,并根据服务器响应调整代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值