zoukankan      html  css  js  c++  java
  • NET后台访问URL获取返回值

    最近在做通过新浪IP地址查询接口查询用户IP是否是国内IP

     1    string strBuff = "";
     2    string url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip="+IP;
     3    Uri httpURL = new Uri(url);
     4    //HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换   
     5    HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
     6    //通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换   
     7    HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
     8    //GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容   
     9    //若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理   
    10    Stream respStream = httpResp.GetResponseStream();
    11    //返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以   
    12    //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)   
    13    StreamReader respStreamReader = new StreamReader(respStream, System.Text.Encoding.UTF8);
    14    strBuff = respStreamReader.ReadToEnd();
    15    if (strBuff != "-2")//127.0.0.1返回值是-2
    16    {
    17       strBuff = strBuff.Substring(strBuff.IndexOf("=") + 1).TrimEnd(';');
    18       SinaIPAPI model = Newtonsoft.Json.JsonConvert.DeserializeObject<SinaIPAPI>(strBuff);//为了方便使用返回JSON,转换为Sina返回实体类,实体类自己后台生成
    19       if (model.ret == 1 && model.country == "u4e2du56fd")//(Unicode编码)u4e2du56fd为中国的意思
    20           dal.InsertUserChina(UID, 1);
    21       else if (model.ret == 1 && model.country != "u4e2du56fd")
    22           dal.InsertUserChina(UID, 0);
    23     }                   
  • 相关阅读:
    C# 英语纠错 LanguageTool
    WPF TreeView 虚拟化-设置滚动到选中项
    C# 同步更新系统时间
    C# 重置IE安全等级
    C# IE环境
    C# IE环境
    WPF ObservableCollection 异步调用问题
    C# 以函数Action/Func/Task作为方法参数
    WPF Geometry 引用Path数据
    ResourceDictionary主题资源替换(一) :通过加载顺序来覆盖之前的主题资源
  • 原文地址:https://www.cnblogs.com/huodetiantang/p/8990149.html
Copyright © 2011-2022 走看看