C#使用WebRequest调用WebApi的方法

Posted progress-everyday

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#使用WebRequest调用WebApi的方法相关的知识,希望对你有一定的参考价值。

1:Get: 

 public static string HttpGetJsonAPI(string uri)
        
            try
            
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Method = "GET";
                webRequest.ContentType = "application/json";
                webRequest.Accept = "application/json";
                 webRequest.Headers.Add("Authorization", GlobalVariable.NowLoginUser.JwtKey);

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                String res = reader.ReadToEnd();
                reader.Close();
                return res.Trim();
            
            catch (Exception ex)
            

                return null;
            

        

2:Post:

public static string HttpPostJsonAPI(string uri, string parameters,string Type, string token = "")

try

byte[] bytes = Encoding.UTF8.GetBytes(parameters);//这里需要指定提交的编码
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
if (GlobalVariable.NowLoginUser == null)
webRequest.Headers.Add("token", "");
else webRequest.Headers.Add("token", GlobalVariable.NowLoginUser.JwtKey);

webRequest.ContentLength = bytes.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
String res = reader.ReadToEnd();
reader.Close();
return res.Trim();

catch (Exception ex)

return null;


3:将获取到的数据转换为相应实体类:

   public static List<T> GetData<T>(Dictionary<string, string> dicNamwValue, string FunTitile, EnumWebType enumType)
        
            try
            
              
                string strurl = GlobalVariable.WebRemotelyIP + FunTitile;// ;
                List<T> listPcaSumData = new List<T>();
                foreach (var item in dicNamwValue)
                
                    strurl = strurl + item.Key + "=" + item.Value + "&";
                
                strurl = strurl.Substring(0, strurl.LastIndexOf("&"));
                string strapi = null;
                if (enumType == EnumWebType.Get)
                    strapi = HttpGetJsonAPI(strurl);
                else strapi = HttpPostJsonAPI(strurl, string.Empty, EnumWebType.Post.ToString());
                if (strapi != null)
                

                    JObject json1 = (JObject)JsonConvert.DeserializeObject(strapi);

                    JValue jTotalCount = (JValue)json1[OrigriUserInfo.totalCount];
                    Type tokenType = json1[OrigriUserInfo.data].GetType();
                    switch (tokenType.FullName)
                    
                        case "Newtonsoft.Json.Linq.JArray":
                            JArray array = (JArray)json1[OrigriUserInfo.data];
                            foreach (var jObject in array)
                            
                                listPcaSumData.Add(JsonConvert.DeserializeObject<T>(jObject.ToString()));
                            
                            break;
                        case "Newtonsoft.Json.Linq.JValue":
                            JValue jdata = (JValue)json1[OrigriUserInfo.data];
                            listPcaSumData.Add(JsonConvert.DeserializeObject<T>(jdata.ToString()));
                            break;

                    
                    return listPcaSumData;
                
                else
                    return null;
            
            catch (Exception ex)
            
                return null;
            

        

       

 

以上是关于C#使用WebRequest调用WebApi的方法的主要内容,如果未能解决你的问题,请参考以下文章

C# winform如何登陆web

(40)C#里使用WebRequest和出错:请求被中止: 未能创建 SSL/TLS 安全通道

(40)C#里使用WebRequest和出错:请求被中止: 未能创建 SSL/TLS 安全通道

通过HTTP请求WEBAPI的方式

C#实现SOAP调用WebService

c# JSON REST 响应通过 3 种不同的方法(WebRequest、RESTSharp、HttpClient)是空的,但 Postman 和浏览器可以工作