C# 通过接口 post 请求

复制代码
        /// <summary>
        /// 提交数据请求  方法一
        /// </summary>
        /// <param name="POSTURL">请求提交的地址 如:http://xxx.xxx.xxx/interface/TestPostRequest</param>
        /// <param name="PostData">提交的数据(字符串)</param>
        /// <returns></returns>
        public static string RequestData(string POSTURL, string PostData)
        {
            //发送请求的数据
            WebRequest myHttpWebRequest = WebRequest.Create(POSTURL);
            myHttpWebRequest.Method = "POST";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byte1 = encoding.GetBytes(PostData);
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = byte1.Length;
            Stream newStream = myHttpWebRequest.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            newStream.Close();

            //发送成功后接收返回的XML信息
            HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
            string lcHtml = string.Empty;
            Encoding enc = Encoding.GetEncoding("UTF-8");
            Stream stream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(stream, enc);
            lcHtml = streamReader.ReadToEnd();
            return lcHtml;
        }

复制代码
        /// <summary>
        /// 通过接口提交请求的公用方法   方法二
        /// </summary>
        /// <param name="url">请求的接口地址  如:http://xxx.xxx.xxx/interface/TestPostRequest</param>
        /// <param name="senddata">要发送的报文</param>
        /// <returns></returns>
        public string GetPostStr(string url, string senddata)
        {
            System.Net.WebClient webc = new System.Net.WebClient();
            var apiurl = new Uri(url);
            string sendstr = senddata;
            webc.Headers.Add("Content-Type", "text/xml");
            //webc.Headers["Content-Type"] = "application/stream;charset=utf-8";//OK  
            var arr = webc.UploadData(apiurl, Encoding.UTF8.GetBytes(sendstr)); 
            return Encoding.UTF8.GetString(arr) ;
        }
复制代码

 




复制代码
        /// <summary>
        /// 服务端接收请求、处理并返回响应的数据
        /// </summary>
        public void TestPostRequest()
        {
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String xmlData = reader.ReadToEnd();

            //string strRequestData = "接收到的请求数据是:" + xmlData;
            //string strReponseData = "要返回的数据是:" + "<root><attReaderName>1</attReaderName></root>";
            string strReponseData= "";
            strReponseData+= "<root>" +
                       "<head>" +
                       "<errorCode>0</errorCode>" +
                       "<result>success</result>" +
                       "</head>" +
                       "</root>";

            HttpContext.Current.Response.Write(strReponseData);
        }
复制代码

 

 
----------Database-------------- 1.DataTable帮助类(DataTableHelper.cs) 2.Access数据库文件操作辅助类(JetAccessUtil.cs) 5.查询条件组合辅助类(SearchCondition.cs) 6.查询信息实体类(SearchInfo.cs) 8.Sql命令操作函数(可用于安装程序的时候数据库脚本执行)(SqlScriptHelper.cs) ----------Device-------------- 声音播放辅助类(AudioHelper.cs) 摄像头操作辅助类,包括开启、关闭、抓图、设置等功能(Camera.cs) 提供用于操作【剪切板】的方法(ClipboardHelper.cs) 获取电脑信息(Computer.cs) 提供用户硬件唯一信息的辅助类(FingerprintHelper.cs) 读取指定盘符的硬盘序列号(HardwareInfoHelper.cs) 提供访问键盘当前状态的属性(KeyboardHelper.cs) 全局键盘钩子。这可以用来在全球范围内捕捉键盘输入。(KeyboardHook.cs) 模拟鼠标点 击(MouseHelper.cs) 全局鼠标钩子。这可以用来在全球范围内捕获鼠标输入。(MouseHook.cs) MP3文件播放操作辅助类(MP3Helper.cs) 关联文件(ExtensionAttachUtil.cs) 注册文件关联的辅助类(FileAssociationsHelper.cs) 打开、保存文件对话框操作辅助类(FileDialogHelper.cs) 常用的文件操作辅助类FileUtil(FileUtil.cs) INI文件操作辅助类(INIFileUtil.cs) 独立存储操作辅助类(IsolatedStorageHelper.cs) 序列号操作辅助类(Serializer.cs) 获取一个对象,它提供用于访问经常引用的目录的属性。(SpecialDirectories.cs) 简单的Word操作对象(WordCombineUtil.cs) 这个类提供了一些实用的方法来转换XML和对象。(XmlConvertor.cs) XML操作类(XmlHelper.cs) ----------Format-------------- 参数验证的通用验证程序。(ArgumentValidation.cs) 这个类提供了实用方法的字节数组和图像之间的转换。(ByteImageConvertor.cs) byte字节数组操作辅助类(BytesTools.cs) 处理数据类型转换,数制转换、编码转换相关的类(ConvertHelper.cs) CRC校验辅助类(CRCUtils.cs) 枚举操作公共类(EnumHelper.cs) 身份证操作辅助类(IDCardHelper.cs) 检测字符编码的类(IdentifyEncoding.cs) RGB颜色操作辅助类(MyColors.cs) 日期操作类(MyDateTime.cs) 转换人民币大小金额辅助类(RMBUtil.cs) 常用的字符串常量(StringConstants.cs) 简要说明TextHelper。(StringUtil.cs) 获取中文字首字拼,随机发生器,按指定概率随机执行操作(Util.cs) 各种输入格式验证辅助类(ValidateUtil.cs) ----------Network-------------- Cookie操作辅助类(CookieManger.cs) FTP操作辅助类(FTPHelper.cs) HTML操作类(HttpHelper.cs) 网页抓取帮助(HttpWebRequestHelper.cs) Net(NetworkUtil.cs) IE代理设置辅助类(ProxyHelper.cs) ----------Winform-------------- 跨线程的控件安全访问方式(CallCtrlWithThreadSafety.cs) CheckBoxList(CheckBoxListUtil.cs) 窗口管理类(ChildWinManagement.cs) 由马丁·米勒http://msdn.microsoft.com/en-us/library/ms996492.aspx提供一个简单的方法打印工作的一个RichTextBox一个帮手(ExRichTextBoxPrintHelper.cs) 显示,隐藏或关闭动画形式。(FormAnimator.cs) 对窗体进行冻结、解冻操作辅助类(FreezeWindowUtil.cs) 窗体全屏操作辅助类(Ful
### 使用 C# 创建和发送 POST 请求 #### HttpClient 类 (推荐) 对于现代 .NET 应用程序,`HttpClient` 是发起 HTTP 请求的最佳选择之一。下面是一个利用 `HttpClient` 发送 JSON 数据作为 POST 请求的例子[^1]。 ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class PostExample { private static async Task Main(string[] args) { var client = new HttpClient(); // 设置目标URL string url = "https://example.com/api/resource"; // 准备要发送的数据对象并序列化为JSON字符串 var content = new StringContent( "{\"key\":\"value\"}", Encoding.UTF8, "application/json" ); try { HttpResponseMessage response = await client.PostAsync(url, content); if(response.IsSuccessStatusCode){ string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response Body: {responseBody}"); } } catch(Exception ex) { Console.WriteLine(ex.Message); } // Dispose the client when done. client.Dispose(); } } ``` 此代码片段展示了如何实例化 `HttpClient`, 构建请求体以及处理响应的过程。注意这里使用了异步编程模型来提高性能效率。 另外,在某些情况下可能需要发送其他类型的编码数据比如 URL 编码形式(`application/x-www-form-urlencoded`) 或 XML 格式的文档。此时可以调整 `StringContent` 的第二个参数指定不同的 MIME 类型,并相应修改待传输的内容格式[^3]。 为了简化从服务器接收到的响应读取过程,可采用如下辅助函数: ```csharp private static string GetResponseString(HttpWebResponse webresponse) { using(Stream s = webresponse.GetResponseStream()) { StreamReader reader = new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd(); } }[^2] ``` 上述方法能够方便地将流转换成字符串表示以便进一步解析或展示给用户。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值