首页 > 编程语言 >C# 与WEB 服务器通信

C# 与WEB 服务器通信

时间:2022-12-29 11:47:30浏览次数:46  
标签:WEB return string C# request using var 服务器 public

与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;
            }
        }

 

标签:WEB,return,string,C#,request,using,var,服务器,public
From: https://www.cnblogs.com/ckrgd/p/17012045.html

相关文章

  • UE4 动态添加/删除蓝图Actor三维模型
    应用场景:想通过业务数据动态添加飞机/车辆等模型到三维机场,并且能根据需求移除指定的三维模型。一,动态添加三维模型的代码:1FStringblueprintName=TEXT("Bluepr......
  • pytorch:二分类时的loss选择
    PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用这里就总结一下使用PyTorch做二分类时的几种情况:总体上来讲,有三种实现形式:最后分类层降至一维,使用sigmo......
  • C# 高级语法混合简单示例(接口、索引器)
    程序集如下  usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSyst......
  • anaconda peompt 、labalimg 数据标注
    安装anaconda,进行数据标注1.安装前准备:下好安装包和所需文件https://www.aliyundrive.com/s/XyH2JQ5TjCz提取码:3c2w2.运行anaconda安装包,解压labelimg-master文件......
  • SiteFactory支持Word图片上传
    ​ 自动导入Word图片,或者粘贴Word内容时自动上传所有的图片,并且最终保留Word样式,这应该是Web编辑器里面最基本的一个需求功能了。一般情况下我们将Word内容粘贴到Web编辑......
  • LPCG:用激光点云指导单目的3D物体检测
    本文推荐浙大团队的一项研究成果:LPCG:LidarPointCloudGuidedMonocular3DObjectDetection,该论文被ECCV2022接收。LPCG:用激光点云指导单目的3D物体检测如果用激光点云......
  • K6 —— load test —— scalability to reliability
    官网: https://k6.io/ feature:      https://k6.io/open-source/      https://k6.io/docs/ ......
  • GCC 版本对应的 libstdc++ 库版本
    GCC版本GLibCC++ABIlibstdc++.so版本GCC3.0.0libstdc++.so.3.0.0GCC3.0.1libstdc++.so.3.0.1GCC3.0.2libstdc++.so.3.0.2GCC3.0.3......
  • 深入理解 c# 第十一章 Cast,OfType和显式类型的范围变量
    classCastAndOfType{staticvoidMain(){ArrayListlist=newArrayList{"First","Second","Third"};//lis......
  • Centos7重置root密码
    如果忘记root密码,可以按以下步骤进行密码重置第一步在启动页面选择内核版本页面,按e进入编辑模式:  拉到后面,将ro改为rw,在这行后面加上init=/bin/sh    按ct......