C#使用WebClient与WebRequest有啥不同

Posted

tags:

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

参考技术A HttpWebRequest
类对
WebRequest
中定义的属性和方法提供支持,也对使用户能够直接与使用
HTTP
的服务器交互的附加属性和方法提供支持。不要使用
HttpWebRequest
构造函数。
使用
WebRequest.Create
方法初始化新的
HttpWebRequest
对象。
如果统一资源标识符
(URI)
的方案是
http://

https://,则Create
返回
HttpWebRequest
对象。
WebClient继承Component类,他集成了
MarshalByRefObject,
IComponent,
IDisposable类,所以使用WebClient,它是最简单的.NET类,它可以响应用户的一般请求,然后处理响应,

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#使用WebClient与WebRequest有啥不同的主要内容,如果未能解决你的问题,请参考以下文章

c# 获取网页源码

如何使用程序调用webApi接口

C#怎么用Socket模拟 HTTP请求

c# WebRequest 使用 WebBrowser cookie

使用WebClient实现断点续传 重写

C# WebClient 禁用缓存