C#关于HttpClient的应用(一):获取IP所在的地理位置信息

    public class IpHttpClient:BaseHttpClient
    {
        private String appKey;
        private const string HOST_PATH = "http://apis.baidu.com/apistore/iplookupservice/iplookup";

        public IpHttpClient()
        {
            this.appKey = BaseHelper.GetValue("BaiduAppKey");
        }

        /// <summary>
        /// HTTP 验证
        /// </summary>
        /// <returns></returns>
        public override Dictionary<string, string> Authorization()
        {
            return new Dictionary<string, string> {{"apikey", this.appKey}};
        }

        /// <summary>
        /// 返回当前Ip所在的地理位置信息
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public ResultDTO GetIpAddress(string ip)
        {
            var reqParams = new Dictionary<String, String>
            {
                {"ip", ip}
            };

            var data = this.SendRequest(Method.Get, HOST_PATH, this.BuildQueryStr(reqParams));
            var result= JsonHelper.ToObject(data.info.ToString());
            if (data.status && Convert.ToInt32(result["errNum"]) == 0)
            {
                var address = JsonHelper.ToObject(result["retData"].ToString());
                return WebApi.Success(address["country"].ToString() + address["province"] + address["city"]);
            }
            return WebApi.Error(data.info);
        }
    }

 

posted @ 2016-02-21 15:13  徐航  阅读(1410)  评论(0编辑  收藏  举报