C#使用HttpClient发送get或post请求

这个博客展示了如何在C#中利用HttpClient类进行POST和GET数据的操作。代码包括了发送JSON对象的POST请求和带有查询参数的GET请求,是进行异步HTTP通信的基础示例。

代码例子如下:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleAppClient
{
    public class HttpHelper
    {

        public static string PostData(string url, object jsonOBJ)
        {
            string postResponse = "";

            try
            {
                using (HttpClient hpc = new HttpClient())
                {
                    //hpc.BaseAddress = new Uri(url);
                    HttpContent httpContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(jsonOBJ));
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                    postResponse = hpc.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return postResponse;
        }

        public static string GetData(string url, Dictionary<string, string> dic)
        {
            string getResponse = "";
            try
            {
                using (HttpClient hpc = new HttpClient())
                {
                    string para = "?";
                    foreach (var item in dic)
                    {
                        para += string.Format("{0}={1}&", item.Key, item.Value);
                    }
                    para = para.TrimEnd('&');

                    if (dic.Count == 0)
                    {
                        para = para.TrimEnd('?');
                    }

                    hpc.BaseAddress = new Uri(url);
                    getResponse = hpc.GetAsync(para).Result.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return getResponse;
        }

    }



}

HttpClient还可以做异步的请求发送,有时间再慢慢研究

C#中,使用`HttpClient`发送POST请求并携带XML数据可以按以下步骤实现。首先需要将数据序列化为XML格式,然后通过`HttpClient`发送请求。 以下是一个示例代码,展示了如何使用`HttpClient`发送POST请求并携带XML数据: ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; // 假设这是要发送的数据类 public class Patient { public string Name { get; set; } public int Age { get; set; } } // 辅助类用于序列化对象为XML public static class XmlHelper { public static string Serilize(object obj) { var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); using (var writer = new System.IO.StringWriter()) { serializer.Serialize(writer, obj); return writer.ToString(); } } } class Program { static async Task Main() { // 创建要发送的数据对象 var patient = new Patient { Name = "John Doe", Age = 30 }; // 序列化数据为XML var send = XmlHelper.Serilize(patient); // 创建StringContent对象,设置内容类型为application/xml StringContent formContent = new StringContent(send, Encoding.Default, "application/xml"); // 创建HttpClient实例 HttpClient httpClient = new HttpClient(); // 设置最大响应内容缓冲区大小 httpClient.MaxResponseContentBufferSize = 256000; // 目标URL string Url = "https://example.com/api/endpoint"; // 发送POST请求 HttpResponseMessage response = await httpClient.PostAsync(new Uri(Url), formContent); // 设置接收参数格式 var contentType = response.Content.Headers.ContentType; if (string.IsNullOrEmpty(contentType.CharSet)) { contentType.CharSet = "GBK"; } // 请求接收参数 var result = await response.Content.ReadAsStringAsync(); // 判断返回参数是否成功 if (response.StatusCode != System.Net.HttpStatusCode.OK) { // 处理请求失败的情况 } Console.WriteLine(result); } } ``` 在上述代码中,首先定义了一个`Patient`类来表示要发送的数据。`XmlHelper`类用于将对象序列化为XML字符串。然后创建`HttpClient`实例,设置请求内容为XML格式,并发送POST请求。最后处理响应结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值