using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xfrog.Net;
using System.Diagnostics;
using System.Web;
using System.Web.Mvc;
using DC.BE.BusinessImpl.Exceptions;
using DC.BE.Entity.ERP;
using Kendo.Mvc;
using Newtonsoft.Json;
using JsonObject = Xfrog.Net.JsonObject;
namespace DC.Website.MVC5.Controllers
{
public class WeatherController : Controller
{
public ActionResult JokeView()
{
return View("~/Views/Tools/Joke.cshtml");
}
public ActionResult XingZuoView()
{
return View("~/Views/Tools/XingZuo.cshtml");
}
public ActionResult HuiLvView()
{
return View("~/Views/Tools/HuiLv.cshtml");
}
public ActionResult LiShiView()
{
return View("~/Views/Tools/LiShi.cshtml");
}
//----------------------------------
// 天气预报调用示例代码 - 聚合数据
// 在线接口文档:http://www.juhe.cn/docs/73
// 代码中JsonObject类下载地址:http://download.csdn.net/download/gcm3206021155665/7458439
//----------------------------------
public JsonResult Weather(string ip)
{
try
{
ip=string.IsNullOrEmpty(ip)?GetIP():ip;
JsonObject obj = GetCityByIp(ip);
string area = Convert.ToString(obj["result"]["area"]);
int sheng = area.IndexOf('省') + 1;
string city = area.Substring(sheng).Replace("'", "");
//1.根据城市查询天气
string url1 = "http://op.juhe.cn/onebox/weather/query";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("cityname", city); //要查询的城市,如:温州、上海、北京
parameters1.Add("key", "5a197c54767ff03fccbed65b7b525146");//你申请的key
parameters1.Add("dtype", "json"); //返回数据的格式,xml或json,默认json
string result1 = sendPost(url1, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0068", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
#region 取ip地址
/// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns>若失败则返回回送地址</returns>
public string GetIP()
{
//如果客户端使用了代理服务器,则利用HTTP_X_FORWARDED_FOR找到客户端IP地址
var _userHostAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
string userHostAddress = string.Empty;
if (_userHostAddress != null && _userHostAddress.IndexOf(',') != -1)
{
userHostAddress = _userHostAddress.ToString().Split(',')[0].Trim();
}
//否则直接读取REMOTE_ADDR获取客户端IP地址
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
//前两者均失败,则利用Request.UserHostAddress属性获取IP地址,但此时无法确定该IP是客户端IP还是代理IP
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
}
//最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
if (!string.IsNullOrEmpty(userHostAddress) && System.Text.RegularExpressions.Regex.IsMatch(userHostAddress, @"^((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)$"))
{
return userHostAddress;
}
return "127.0.0.1";
}
#endregion
public JsonObject GetCityByIp(string ip)
{
try
{
//"110.104.26.65"
//1.根据IP/域名查询地址
string url1 = "http://apis.juhe.cn/ip/ip2addr";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("ip", ip); //需要查询的IP地址或域名
parameters1.Add("key", "df4660c52057c05743ced48cb47fbbc6");//你申请的key
parameters1.Add("dtype", "json"); //返回数据的格式,xml或json,默认json
string result1 = sendPost(url1, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "城市", errorCode1);
}
//var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return newObj1;
}
catch (Exception)
{
return null;
}
}
public JsonResult Joke()
{
try
{
string url = "http://japi.juhe.cn/joke/content/list.from";
var parameters1 = new Dictionary<string, string>();
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string time = Convert.ToInt64(ts.TotalSeconds).ToString();
parameters1.Add("sort", "desc"); //类型,desc:指定时间之前发布的,asc:指定时间之后发布的
parameters1.Add("page", "1"); //当前页数,默认1
parameters1.Add("pagesize", "20"); //每次返回条数,默认1,最大20
parameters1.Add("time", time); //时间戳(10位),如:1418816972
parameters1.Add("key", "12c41a4dfca129cc4bc8208670f4e34c");//你申请的key
string result1 = sendPost(url, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "笑话", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
public JsonResult LiShi()
{
try
{
string url = "http://api.juheapi.com/japi/toh";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("key", "1cd7e43fcf6fe8084b535a493be52616");//你申请的key
parameters1.Add("v", "1.0"); //版本,当前:1.0
parameters1.Add("month", DateTime.Now.Month.ToString()); //月份,如:10
parameters1.Add("day", DateTime.Now.Day.ToString()); //日,如:1
string result1 = sendPost(url, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "历史", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
public JsonResult XingZuo(string consName)
{
try
{
//1.运势查询
string url1 = "http://web.juhe.cn:8080/constellation/getAll";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("key", "ca7552d54496645a526ab753b367e8fe");//你申请的key
parameters1.Add("consName", consName); //星座名称,如:白羊座
parameters1.Add("type", "today"); //运势类型:today,tomorrow,week,nextweek,month,year
string result1 = sendPost(url1, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "星座", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
public JsonResult HuiLv()
{
try
{
string url = "http://op.juhe.cn/onebox/exchange/query";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("key", "cba6fa5c81b9be5c3483b81ec958b98a");//你申请的key
string result1 = sendPost(url, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "汇率", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
public JsonResult HuoBiList()
{
try
{
string url = "http://op.juhe.cn/onebox/exchange/list";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("key", "cba6fa5c81b9be5c3483b81ec958b98a");//你申请的key
string result1 = sendPost(url, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "汇率", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
public JsonResult FromTo(string from,string to)
{
try
{
string url = "http://op.juhe.cn/onebox/exchange/currency";
var parameters1 = new Dictionary<string, string>();
parameters1.Add("from", from); //转换汇率前的货币代码
parameters1.Add("to", to); //转换汇率成的货币代码
parameters1.Add("key", "cba6fa5c81b9be5c3483b81ec958b98a");//你申请的key
string result1 = sendPost(url, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 != "0")
{
throw new BaseBusinessExceptionWithErrorCode("ERPE0069", "换算", errorCode1);
}
var jsonObj = JsonConvert.DeserializeObject<object>(result1);
return this.JsonNewton(jsonObj);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Http (GET/POST)
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="parameters">请求参数</param>
/// <param name="method">请求方法</param>
/// <returns>响应内容</returns>
public string sendPost(string url, IDictionary<string, string> parameters, string method)
{
if (method.ToLower() == "post")
{
HttpWebRequest req = null;
HttpWebResponse rsp = null;
System.IO.Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = method;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Timeout = 5000;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (reqStream != null) reqStream.Close();
if (rsp != null) rsp.Close();
}
}
else
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
//GET请求
request.Method = "GET";
request.ReadWriteTimeout = 5000;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
//返回内容
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
public string BuildQuery(IDictionary<string, string> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}
/// <summary>
/// 把响应流转换为文本。
/// </summary>
/// <param name="rsp">响应流对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>响应文本</returns>
public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
System.IO.Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
}
}