首页 > 编程语言 >C# http接口请求

C# http接口请求

时间:2023-01-06 15:01:11浏览次数:72  
标签:http string C# request 接口 ex response 请求

方法一:Get请求:

 /// <summary>
        /// httpRequest 
        /// </summary>
        /// <param name="url">http接口路径</param>
        /// <returns>将http接口信息进行返回</returns>
        public string httpRequest(string Url)
        {
            string retString = string.Empty;
            try
            {
                LogHelper.WriteLog(GetType(), "httpRequest方法接收入参为:" + Url);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Proxy = null;
                request.KeepAlive = false;
                request.Method = "GET";
                request.ContentType = "application/json; charset=UTF-8";
                request.AutomaticDecompression = DecompressionMethods.GZip;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                //retString = System.Text.RegularExpressions.Regex.Unescape(retString);//字符串转义
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }

            }
            catch (Exception ex)
            {

                LogHelper.WriteLog(GetType(), "httpRequest方法异常错误为:" + ex.Message);
            }
            LogHelper.WriteLog(GetType(), "httpRequest方法接收返回值为:" + retString);
            return retString;
        }

  方法二Post请求:

 string url = "http://192.168.1.219:8088/system-demo-newui/public/index.php/zizhu/menzhen/hospital/getAdvert";//获取http地址
        string json = "{\"devCode\":\"H000_0102\"}";//获取传参json串
        public void cesi()
        {
            Post(url, json);
        }
        /// <summary>
        /// post请求http接口
        /// </summary>
        /// <param name="Url">http接口路径</param>
        /// <param name="jsonParas">传参json串</param>
        /// <returns></returns>
        public string Post(string Url, string jsonParas)
        {
            string postContent = string.Empty;
            HttpWebResponse response;
            try
            {
                LogHelper.WriteLog(GetType(), "进入Post方法,入参为:" + Url + ",入参2为:" + "jsonParas");
                string strURL = Url;
                //创建一个HTTP请求  
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式  
                request.Method = "POST";
                //内容类型
                request.ContentType = "application/json";
                //设置参数,并进行URL编码 
                string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   
                byte[] payload;
                //将Json字符串转化为字节  
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                //设置请求的ContentLength   
                request.ContentLength = payload.Length;
                //发送请求,获得请求流 
                Stream writer;
                try
                {
                    writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
                }
                catch (Exception ex)
                {
                    writer = null;
                    LogHelper.WriteLog(GetType(), "Post获取用于写入请求数据的Stream对象异常错误:" + ex.Message);
                    //  Console.Write("连接服务器失败!");
                }
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                writer.Close();//关闭请求流
                               // String strValue = "";//strValue为http响应所返回的字符流
                try
                {
                    //获得响应流
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    response = ex.Response as HttpWebResponse;
                }
                Stream s = response.GetResponseStream();
                //  Stream postData = Request.InputStream;
                StreamReader sRead = new StreamReader(s);
                postContent = sRead.ReadToEnd();
                sRead.Close();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(GetType(), "Post请求接口异常错误:" + ex.Message);
            }
            return postContent;//返回Json数据
        }

  

 

标签:http,string,C#,request,接口,ex,response,请求
From: https://www.cnblogs.com/lydj/p/17030502.html

相关文章

  • linux的centos7安装mysql5.7服务教程
    1.使用yum安装,便捷,快速MySQLYumRepositoryMySQL官方新提供了一种安装MySQL的方法--使用YUM源安装MySQL.1、MySQL官方网站下载MySQL的YUM源,在MySQL的下载页有一个“NEW!My......
  • Linux-Windows-Mac-Redis安装教程
    说明本说明分一下三种方式安装,请根据具体环境选择相关版本。linux服务器安装win版服务器安装mac版安装linux服务器安装(本文档不含Redis集群的搭建,具体搭建方案请参考《​​......
  • 微服务(入门学习五):identityServer4+ocelot+consul实现简单客户端模式
    简介 主要是采用identityServer4和ocelot加上consul实现简单的客户端模式  开发准备 环境准备下载并安装Consul具体请参考前几篇的内容项目介绍创建oc......
  • ubuntu 安装elasticsearch
    elasticsearch简介  环境准备 elasticsearch:7.0.0 kibana     :7.0.0 安装 1.新创建普通用户 elasticsearch不能用root账号启动,为了避免之后......
  • .Net Core 中间件
    自定义中间件的使用在项目启动配置文件中Configure方法publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){ app.UseMiddleware<CorsMiddlewar......
  • 微服务(入门二):netcore通过consul注册服务
    基础准备1.创建asp.netcoreWeb应用程序选择Api2.appsettings.json配置consul服务器地址,以及本机ip和端口号信息 {"Logging":{"LogLevel":{"D......
  • Copy a Conda env to another machine
    ThefollowingsulutionsarefromchatGPTandhasbeenverified.1.TocopyaCondaenvironmentfromoneLinuxmachinetoanother,youcanusethecondaenvexp......
  • docker安装centos7
    一、查看可用的CentOS版本访问CentOS镜像库地址:https://hub.docker.com/_/centos?tab=tags&page=1。可以通过Sortby查看其他版本的CentOS。默认是最新版本cent......
  • 微服务(入门一):netcore安装部署consul(windows)
    环境准备 vs开发环境:vs2017 consul版本: 1.4.4 netcore版本:2.1安裝Consul 1.从官网下载consul到本地,选择系统对应的版本进行下载到本地,下载地址:https://www.consu......
  • CentOS7.9下配置安装KVM虚拟机
     一、准备工作:1.关闭selinux、防火墙##关闭selinux#sed-i's/SELINUX=enforcing/SELINUX=disabled/g'/etc/selinux/config#永久生效,但是必须要重启系统。##立......