【C#】C#调用http请求,HttpWebRequest添加http请求头信息

作为桌面程序开发老鸟,最近经常涉及到与各大web接口对接,调用对方webapi 的业务需要。
无奈写下此小工具,方便后期摘抄,也希望能帮助到需要的你。

那么先看调用效果吧

  • 把post和get放在一起调用了 都调用成功的情况
    【C#】C#调用http请求,HttpWebRequest添加http请求头信息_第1张图片
  • 主机不存在的情况
    【C#】C#调用http请求,HttpWebRequest添加http请求头信息_第2张图片
  • 服务端错误情况
    【C#】C#调用http请求,HttpWebRequest添加http请求头信息_第3张图片

完整代码

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

namespace http
{
    class Program
    {
        static void Main(string[] args)
        {            
            string Datas = @"{ ""cainfo"": ""1"", ""dev_no"": ""1"", ""dev_safe_info"": ""1"", ""fixmedins_code"": ""060070"", ""fixmedins_name"": ""朝阳医院"", ""inf_time"": ""2020-09-29 02:49:11"", ""infno"": ""1101"", ""infver"": ""V1.0"", ""insuplc_admdvs"": ""340600"", ""mdtrtarea_admvs"": ""340600"", ""msgid"": ""1232342423"", ""opter"": ""14"", ""opter_name"": ""csb-测试"", ""opter_type"": ""1"", ""recer_sys_code"": ""1"", ""sign_no"": ""1"", ""signtype"": ""1"" }";
            //调用post请求 
            string retString = httpPost("http://127.0.0.1/admin/ajax/test", Datas);
           
            //调用get请求
            string retString2 = httpGet("http://127.0.0.1/admin/ajax/test");            
            //http://csb-broker.cloud.ahhb.hsip.gov.cn:8086/1.0.0/hsa-fsi-1101

            Console.WriteLine(retString);
            Console.WriteLine("--===========↑上面是post请求返回的数据 ↓下面是get请求返回的数据===============");
            Console.WriteLine(retString2);
            Console.ReadKey();
        }


        public static string httpPost(string url,string data) {
           
            string retString = String.Empty;
            string paramData = data;
            //CookieContainer cookie = new CookieContainer();
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://csb-broker.cloud.ahhb.hsip.gov.cn:8086/1.0.0/hsa-fsi-1101");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            //request.Referer = Referer;
            byte[] bytes = Encoding.UTF8.GetBytes(paramData);
            request.Accept = "text/html, application/xhtml+xml, */*";
            //request.ContentType = "application/*";
            request.ContentType = "application/x-www-form-urlencoded";
            //设置C# HttpWebRequest post请求头消息
            request.Headers.Add("version", "1.0.0");
            request.Headers.Add("ak", "45b83b3b780d46028afa1da41dcdd0a4");
            request.Headers.Add("sk", "1+JX1Gsg3hEu4Ui+VdQvWlaz1gY=");
            request.ContentLength = bytes.Length;
            try
            {
                Stream myResponseStream = request.GetRequestStream();
                myResponseStream.Write(bytes, 0, bytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                int statusCode = (int)response.StatusCode;
                if (statusCode == 200)
                {
                    // Console.WriteLine(statusCode);
                    myStreamReader.Close();
                    myResponseStream.Close();

                    if (response != null)
                    {
                        response.Close();
                    }
                    if (request != null)
                    {
                        request.Abort();
                    }
                }
            }
            catch (Exception ex)
            {
                //抛出异常返回具体错误消息
                retString =  ex.Message;
            }
            return retString;          
        }


        public static string httpGet(string Url)
        {
            string retString = string.Empty;
            //System.GC.Collect();
            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;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }catch(Exception ex){
                //抛出异常返回具体错误消息
                retString = ex.Message;
            }
            return retString;
        }
    }
}

你可能感兴趣的:(C#.NET,个人笔记,c#,http)