.net通过url访问服务器获取服务器返回数据
一、url为http协议
方法调用举例:
二、url为https协议
只需加入一句话即可:
1、普通调用:
1、普通调用:
- public string GetInfo(string url)
- {
- //访问http方法
- string strBuff = "";
- Uri httpURL = new Uri(url);
- ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法建立,并进行强制的类型转换
- HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
- ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
- HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
- ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容
- ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理
- Stream respStream = httpResp.GetResponseStream();
- ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以
- //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)
- StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
- strBuff = respStreamReader.ReadToEnd();
- return strBuff;
- }
方法调用举例:
- string url = "http://192.168.1.38:8088/api/user/get_info"; //http协议url
- url +="?token=" + token + "&openid=" + openid ;
- string userInfo = GetInfo(url);
2、json调用(使用Json方法访问url需要在.net3.5以上版本):
- #region Json访问url方式(使用该方法需要在.net3.5以上)
- //获得用户信息
- protected OAuthUser Get_UserInfo(string token , string openid)
- {
- //http协议url
- string Str = GetJson("http://192.168.1.38:8088/api/user/get_info?token=" + token + "&openid=" + openid);
- OAuthUser OAuthUser_Model = JsonHelper.ParseFromJson(Str);
- return OAuthUser_Model;
- }
- protected string GetJson(string url)
- {
- //访问http
- WebClient wc = new WebClient();
- wc.Credentials = CredentialCache.DefaultCredentials;
- wc.Encoding = Encoding.UTF8;
- string returnText = wc.DownloadString(url);
- if (returnText.Contains("errcode"))
- {
- //可能发生错误
- }
- //Response.Write(returnText);
- return returnText;
- }
- ///
- /// 用户信息类
- ///
- public class OAuthUser
- {
- public OAuthUser()
- { }
- #region 数据库字段
- private string _dept;
- private string _name;
- private string _userid;
- #endregion
- #region 字段属性
- ///
- /// 部门
- ///
- public string dept
- {
- set { _dept = value; }
- get { return _dept; }
- }
- ///
- /// 用户名称
- ///
- public string name
- {
- set { _name = value; }
- get { return _name; }
- }
- ///
- /// 用户的唯一标识
- ///
- public string userid
- {
- set { _userid = value; }
- get { return _userid; }
- }
- #endregion
- }
- public class JsonHelper
- {
- ///
- /// 生成Json格式
- ///
- ///
- ///
- ///
- public static string GetJson(T obj)
- {
- DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
- using (MemoryStream stream = new MemoryStream())
- {
- json.WriteObject(stream, obj);
- string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;
- }
- }
- ///
- /// 获取Json的Model
- ///
- ///
- ///
- ///
- public static T ParseFromJson(string szJson)
- {
- T obj = Activator.CreateInstance();
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- return (T)serializer.ReadObject(ms);
- }
- }
- }
- #endregion
- json调用方式举例:
- OAuthUser OAuthUser_Model = Get_UserInfo(token, openid);
- //联调测试
- Response.Write("accesstoken:" + token + "
- userid:" + OAuthUser_Model.userid + "
- 用户名称:" + OAuthUser_Model.name + "
- 部门:" + OAuthUser_Model.dept);
二、url为https协议
只需加入一句话即可:
- //访问https方法(先调用以下方法)
- using System.Security.Cryptography.X509Certificates;
- public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- //直接确认,否则打不开
- return true;
- }
1、普通调用:
- public string GetInfo(string url)
- {
- //访问https方法需加上这句话(CheckValidationResult就是以上方法)
- ServicePointManager.ServerCertificateValidationCallback =
- new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
- //访问http方法(不需要加上面那句话)
- string strBuff = "";
- Uri httpURL = new Uri(url);
- ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法建立,并进行强制的类型转换
- HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
- ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
- HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
- ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容
- ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理
- Stream respStream = httpResp.GetResponseStream();
- ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以
- //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)
- StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
- strBuff = respStreamReader.ReadToEnd();
- return strBuff;
- }
方法调用举例:
- string url = "https://192.168.1.38:8088/api/user/get_info"; //htts协议url
- url +="?token=" + token + "&openid=" + openid ;
- string userInfo = GetInfo(url);
2、Json调用
- //获得用户信息
- protected OAuthUser Get_UserInfo(string token , string openid)
- {
- //htts协议url
- string Str = GetJson("https://192.168.1.38:8088/api/user/get_info?token=" + token + "&openid=" + openid);
- OAuthUser OAuthUser_Model = JsonHelper.ParseFromJson(Str);
- return OAuthUser_Model;
- }
- protected string GetJson(string url)
- {
- //访问https需加上这句话
- ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
- //访问http(不需要加上面那句话)
- WebClient wc = new WebClient();
- wc.Credentials = CredentialCache.DefaultCredentials;
- wc.Encoding = Encoding.UTF8;
- string returnText = wc.DownloadString(url);
- if (returnText.Contains("errcode"))
- {
- //可能发生错误
- }
- //Response.Write(returnText);
- return returnText;
- }
- json调用方式举例:
- OAuthUser OAuthUser_Model = Get_UserInfo(token, openid);
- //联调测试
- Response.Write("accesstoken:" + token + "
- userid:" + OAuthUser_Model.userid + "
- 用户名称:" + OAuthUser_Model.name + "
- 部门:" + OAuthUser_Model.dept);