C# 与WEB 服务器通信

news/2024/7/7 20:25:24

与web服务器通信应先使用postman测试,确认服务器正常再写代码

 

发送UTF-8 的json字符串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Net;

public enum HttpVerb
{
    GET, //method 常用的就这几样,当然你也可以添加其他的 get:获取 post:修改 put:写入 delete:删除
    POST,
    PUT,
    DELETE
}


namespace restPostJsonToWebServer
{
    public class restPostJson
    {
        public restPostJson()
        {
            EndPoint = "";
            Method = HttpVerb.GET;
            ContentType = "text/xml";
            PostData = "";
        }

        public restPostJson(string endpoint)
        {
            EndPoint = endpoint;
            Method = HttpVerb.GET;
            ContentType = "text/xml";
            PostData = "";
        }

        public restPostJson(string endpoint, HttpVerb method)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "text/xml";
            PostData = "";
        }

        public restPostJson(string endpoint, HttpVerb method, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "text/xml";
            PostData = postData;
        }

        public restPostJson(string endpoint, string postData)
        {
            EndPoint = endpoint;
            Method = HttpVerb.POST;
            ContentType = "application/json";
            PostData = postData;
        }

        public string restPostJsonToWebServer(string text)
        {
            return "I'm restPostJson";
        }

        public string EndPoint { get; set; } //请求的url地址
        public HttpVerb Method { get; set; } //请求的方法
        public string ContentType { get; set; } //格式类型application/json
        public string PostData { get; set; } //传送的数据,当然了我使用的是json字符串

        
        public string MakeRequest()
        {
            return MakeRequest("");
        }

        public string MakeRequest(string parameters)
        {
            var responseValue = string.Empty;
            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;

            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)//如果传送的数据不为空,并且方法是post
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("utf-8").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
                request.ContentLength = bytes.Length;

                try
                {
                    using (var writeStream = request.GetRequestStream())
                    {
                        writeStream.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception e)
                {
                    responseValue = "error,";
                    responseValue += e.Message;
                    return responseValue;
                }
            }

            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//如果传送的数据不为空,并且方法是put
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("utf-8").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                        throw new ApplicationException(message);
                    }

                    // grab the response
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                            using (var reader = new StreamReader(responseStream))
                            {
                                responseValue = reader.ReadToEnd();
                            }
                    }

                    return responseValue;
                }
            }
            catch (Exception e)
            {
                //e.Message
                responseValue = "error,GetResponse异常" + e.Message;
                return responseValue;
            }
        }
    }
}

VC 调用代码

#using "../debug/restPostJsonToWebServer.dll"
using namespace restPostJsonToWebServer;

CString restJsonToWebSer(CString strHttpAdd, CString strData)
{
    System::String ^sHttpAdd = gcnew System::String(strHttpAdd);
    System::String ^sdata = gcnew System::String(strData);

    restPostJson ^myRest = gcnew restPostJson(sHttpAdd, sdata);
    CString resultGet = myRest->MakeRequest();

    return resultGet;
}

 如果要发送其他类型的字符串

public string HttpPostAsXWWWFormUrlEncoded(string data, string url)
        {
            string result = "";
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.AllowAutoRedirect = true;
                request.Timeout = 2 * 1000;
                request.ContentType = "application/x-www-form-urlencoded";
                var byteArray = Encoding.Default.GetBytes(data);
                request.ContentLength = byteArray.Length;
                using (var newStream = request.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);
                    newStream.Close();
                }

                var response = (HttpWebResponse)request.GetResponse();
                var rspStream = response.GetResponseStream();
                using (var reader = new StreamReader(rspStream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    rspStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return result;
        }

如果请求头中要加入数据

public string httpHeadAuthorizationPostJson(string ParameterBody, string url, string Token)
        {
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(ParameterBody);
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "application/json"); //采取POST方式必须加的header
                string strHead;
                strHead = "Bearer " + Token;
                webClient.Headers.Add("Authorization", strHead); //采取POST方式必须加的header

                webClient.Headers.Add("ContentLength", postData.Length.ToString());
                byte[] responseData = webClient.UploadData(url, "POST", postData); //得到返回字符流
                string strRes = Encoding.UTF8.GetString(responseData); //解码

                return strRes;
            }
            catch (AggregateException ex)
            {
                MessageBox.Show(ex.Message);
                return ex.Message;
            }
        }

使用WebClient类通信

        public string LocalHttpGet()
        {
            try
            {
                string GetHttpData = "";
                string url = "http://127.0.0.1/api/HeartbeatV1";
                WebClient client = new WebClient();

                byte[] data = client.DownloadData(url);
                GetHttpData = Encoding.UTF8.GetString(data);

                return GetHttpData;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

使用WebClient加一些参数

public string LocalHttpPost(string PostData)
        {
            try
            {
                string url = "http://127.0.0.1/api/TestDetailV1Contriller"; // api路径(请求接口)
                byte[] postData = Encoding.UTF8.GetBytes(PostData);
                WebClient webClient = new WebClient();

                webClient.Headers.Add("accept", "text/plain");
                webClient.Headers.Add("Content-Type", "application/json"); //采取POST方式必须加的header
                webClient.Headers.Add("ContentLength", postData.Length.ToString());

                byte[] responseData = webClient.UploadData(url, "POST", postData); //得到返回字符流
                string strRes = Encoding.UTF8.GetString(responseData); //解码

                return strRes;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

 


http://lihuaxi.xjx100.cn/news/517300.html

相关文章

Windows下MySQL安装配置和工具使用

目录 1、下载地址 1.1、建立配置文件 1.2、初始化数据库 1.3、安装服务

AAAI2023 | 针对联邦推荐场景的非定向攻击与防御

嘿,记得给“机器学习与推荐算法”添加星标TLDR:今天跟大家分享一篇通过利用聚类算法来操纵物品嵌入特征以此针对联邦推荐场景进行非定向攻击的工作,随后作者针对这一攻击又提出了一种基于一致性的对应防御机制,该论文已被AAAI2023…

CIO40— 2022 行平常心,做自由人 (3年之约已满)

今天的天空依然很蓝。认识还是在那个不戴口罩的夏天。 感谢IT行业给了我们帮助。 IT将交流植根于微信群,微信群既是信息的集散地,也是良好实践的方案池。在工作中碰到的问题,只要在IT微信群中求助,大家都是知无不言&#xff0c…

【重要】有三AI技术专栏作者邀请,5大权益助力共同成长

知识分享平台众多,我们有三AI公众号是其中一个,在过去的3年里,我们已经写了700多篇,超过200万字的技术文,其中一些专栏作者的贡献功不可没。我们公众号只做原创内容,因为我并不希望平台成为一个靠复制转载内…

python基础回顾

python基础字符串计算字符串中某个字符或者子字符串出现的次数判断字符串的数据类型字符串子串的查找字符串中子串的数量字符串拼接内置函数执行计算表达式(字符串)去重 set()函数lambda函数类Python动态实例属性判断对象是否存在指定属性给对象添加指定属性字符串 计算字符串…

希尔排序分析

目录 🍅 原理介绍 🍅 特点 🍅 代码示例 🍅 算法复杂度(参考《数据结构》严蔚敏) 🍅 改进方案 🍅 原理介绍 [算法]六分钟彻底弄懂希尔排序,简单易懂_哔哩哔哩_bilib…

【技术分享】如何实现功能完备性能优异的RTMP、RTSP播放器?

技术背景 这几年,我们对接了太多有RTSP或RTMP直播播放器诉求的开发者,他们当中除了寻求完整的解决方案的,还有些是技术探讨,希望能借鉴我们播放端的开发思路或功能特性,完善自己的产品。 忙里偷闲,今天我…

Linux下Qt程序用qBreakpad定位崩溃位置

目录1. 使用qBreakpad1.1. 下载1.2. 编译1.3. 使用2. 使用dump文件2.1. 编译breakpad2.2. 解析dmp文件生成sym文件2.3. 解析dmp可能遇到的问题问题一Qt程序的release版本交付给用户或者测试后,如果出现崩溃,很多时候都比较难重现,如果程序能自…