zoukankan      html  css  js  c++  java
  • C# 调用接口实例httpclient(postman)

    调用主体

    Get请求

    var httpClient = new HttpClient();            
                var getTokenUrl = new Uri("接口网络地址");
                var response = httpClient.GetAsync(getTokenUrl).Result;
                var data = response.Content.ReadAsStringAsync().Result;//接口调用成功获取的数据
                JObject jsonInfo = (JObject)JsonConvert.DeserializeObject(data);
                string code = Convert.ToString(jsonInfo["errcode"]);
    View Code

    Post请求 

    此处例举的是传headers,如果不需要注释掉

    #region 调用接口(postman)
    
                
                string Url = "http://?.?.?.?:9900/weather";//请求的url地址
                //string ContentTypeS = "application/x-www-form-urlencoded"; //格式类型(x-www-form-urlencoded格式传参)
                string ContentTypeS = "application/json"; //格式类型(json格式传参)
    
                //string PostData = "mode=" + "insert" + "&data=" + json;    //传送的数据(x-www-form-urlencoded传参)
                sendCS sendcs = new sendCS();
                sendcs.mode = "insert";
                sendcs.data = "12345";
                string jkid = "12345";
                //转json
                string PostData = JsonConvert.SerializeObject(sendcs);    //传送的数据(json传参)
                RestApiClient DXApiManager = new RestApiClient(Url, HttpVerbNew.POST, ContentTypeS, PostData, jkid);
                string returnInfo = DXApiManager.MakeRequest();
                //转为json对象(添加Newtonsoft.Json.dll引用)
                JObject jsonInfo = (JObject)JsonConvert.DeserializeObject(returnInfo);
                string code = Convert.ToString(jsonInfo["code"]);//输出  结果
                string msg = Convert.ToString(jsonInfo["msg"]);//输出  结果
    
                //再根据code返回值去判断成功或失败,返回结果
    
                #endregion
    View Code

    相关类

    public class RestApiClient
            {
                public string EndPoint { get; set; }    //请求的url地址  
                public HttpVerbNew Method { get; set; }    //请求的方法
                public string ContentType { get; set; } //格式类型
                public string PostData { get; set; }    //传送的数据
                public string JKID { get; set; }    //headers 参数
    
    
                public RestApiClient()
                {
                    EndPoint = "";
                    Method = HttpVerbNew.GET;
                    ContentType = "text/xml";
                    PostData = "";
                }
                public RestApiClient(string endpoint, string contentType)
                {
                    EndPoint = endpoint;
                    Method = HttpVerbNew.GET;
                    ContentType = contentType;
                    PostData = "";
                }
                public RestApiClient(string endpoint, HttpVerbNew method, string contentType)
                {
                    EndPoint = endpoint;
                    Method = method;
                    ContentType = contentType;
                    PostData = "";
                }
    
    
                public RestApiClient(string endpoint, HttpVerbNew method, string contentType, string postData,string jkid)
                {
                    EndPoint = endpoint;
                    Method = method;
                    ContentType = contentType;
                    PostData = postData;
                    JKID = jkid;
                }
    
    
                // 添加https
                private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    
    
                private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
                {
                    if (errors == SslPolicyErrors.None)
                        return true;
                    return false;
                }
                // end添加https
    
    
                public string MakeRequest()
                {
                    return MakeRequest("");
                }
    
    
                public string MakeRequest(string parameters)
                {
                    // 添加https
                    if (EndPoint.Substring(0, 8) == "https://")
                    {
                        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    }
                    var request = (HttpWebRequest)HttpWebRequest.Create(EndPoint + parameters);
                    if (EndPoint.Substring(0, 8) == "https://")
                    {
                        //string clientp12path = AppDomain.CurrentDomain.BaseDirectory + "\Certificate\outgoing.CertwithKey.pkcs12";
                        //string clientp12PassWord = "IoM@1234";
                        //string clientp12path2 = AppDomain.CurrentDomain.BaseDirectory + "\Certificate\server.pem";
                        //string clientp12PassWord2 = "1qaz2wsx";
                        //X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                        //certStore.Open(OpenFlags.ReadOnly);
                        //X509Certificate2 cer = new X509Certificate2(clientp12path, clientp12PassWord);
                        //X509Certificate2 cer2 = new X509Certificate2(clientp12path2, clientp12PassWord2);
                        //request.ClientCertificates.Add(cer);
                        //request.ClientCertificates.Add(cer2);
                        ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                        {
                            return true;
                        };
                        request.UserAgent = DefaultUserAgent;
                    }
                    // end添加https
                    request.Method = Method.ToString();
                    request.ContentLength = 0;
                    request.ContentType = ContentType;
                    request.ProtocolVersion = HttpVersion.Version10;
                    request.Headers.Add("alpha_auth_token", "asdf12345");
                    request.Headers.Add("alpha_auth_jkid", JKID);
    
    
                    if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.POST)//如果传送的数据不为空,并且方法是post
                    {
                        var encoding = new UTF8Encoding();
                        var bytes = Encoding.UTF8.GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
                        request.ContentLength = bytes.Length;
                        using (var writeStream = request.GetRequestStream())
                        {
                            writeStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    else if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.PUT)//如果传送的数据不为空,并且方法是put
                    {
                        var encoding = new UTF8Encoding();
                        var bytes = Encoding.UTF8.GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
                        request.ContentLength = bytes.Length;
                        using (var writeStream = request.GetRequestStream())
                        {
                            writeStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        var responseValue = string.Empty;
                        if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent && response.StatusCode != HttpStatusCode.Created)
                        {
                            var message = response.StatusCode.ToString();
                            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;
                    }
                }
    
    
            }
            public enum HttpVerbNew
            {
                GET,            //method  常用的就这几样,可以添加其他的   get:获取    post:修改    put:写入    delete:删除
                POST,
                PUT,
                DELETE
            }
    View Code

    httpclient万能写法

    现在postman越来越便利,当我们用postman调通接口后,可直接一键成生code(postman版本不同位置不同)

    举例:

     

    点击后可一键生成代码   扔进项目里就可运行 前提!!!需要添加一个NuGet包 --- RestSharp

  • 相关阅读:
    awk,seq,xarg实例使用
    Docker安装yapi
    基于阿里搭载htppd访问
    锐捷结课作业
    基于centos7搭建kvm
    基于django实现简易版的图书管理系统
    python 自定义log模块
    Interesting Finds: 2008.01.13
    Interesting Finds: 2008.01.24
    Interesting Finds: 2008.01.17
  • 原文地址:https://www.cnblogs.com/JoeYD/p/12671975.html
Copyright © 2011-2022 走看看