WebApi现在越来越流行,下面给出利用HttpWebRequest访问WebApi的工具方法:
1、利用基准URL和参数字典生成完整URL
/// <summary>
/// 生成URL字符串
/// </summary>
/// <param name="baseUrl">基准URL</param>
/// <param name="dictParam">参数字典</param>
/// <returns>最终URL字符串</returns>
public static string GetUrl(string baseUrl, Dictionary<string, string> dictParam)
{
if (string.IsNullOrWhiteSpace(baseUrl))
{
throw new ArgumentNullException("baseUrl", "基准URL不能为空");
}
StringBuilder sbParam = new StringBuilder();
string strParam = string.Empty;
if (dictParam != null && dictParam.Count > 0)
{
sbParam.Append("?");
foreach (KeyValuePair<string, string> item in dictParam)
{
sbParam.Append(string.Format("{0}={1}&", item.Key, HttpUtility.UrlEncode(item.Value, Encoding.UTF8)));
}
strParam = sbParam.ToString();
strParam = strParam.Substring(0, strParam.Length - 1);
}
string strUrl = string.Format("{0}{1}", baseUrl, strParam);
return strUrl;
}
2、通过HTTP请求获取数据(参数为非model类型)
/// <summary>
/// 通过http请求获取数据(参数为非model类型)
/// </summary>
/// <param name="url">获取数据的url</param>
/// <param name="requestMethod">请求方法:GET/POST/PUT/DELETE</param>
/// <param name="jsonData">返回的json数据</param>
/// <param name="errMsg">错误信息</param>
/// <returns>true:成功 false:失败</returns>
public static bool RequestHttpData(string url, string requestMethod, out string jsonData, out string errMsg)
{
jsonData = string.Empty;
errMsg = string.Empty;
string result = string.Empty;
try
{
//创建请求
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 15 * 60 * 1000; //15分钟
request.Method = requestMethod;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
//获取数据
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
}
}
catch (WebException ex)
{
try
{
WebResponse wr = ex.Response;
Stream st = wr.GetResponseStream();
StreamReader sr = new StreamReader(st, System.Text.Encoding.Default);
string tmpErr = sr.ReadToEnd();
Regex r = new Regex(@"\<body\>\<h1\>.*\</h1\>");
errMsg = r.Match(tmpErr).Value.Replace("<body><h1>", "").Replace("</h1>", "");
sr.Close();
st.Close();
}
catch
{
errMsg = ex.Message;
}
return false;
}
catch (Exception ex)
{
errMsg = ex.Message;
return false;
}
if (!string.IsNullOrWhiteSpace(result))
{
jsonData = result;
}
return true;
}
3、通过HTTP请求获取数据(参数为model类型)
/// <summary>
/// 通过http请求传递数据(参数为model类型)
/// </summary>
/// <param name="url">传递数据的url</param>
/// <param name="paraJson">要传递的Json数据</param>
/// <param name="requestMethod">请求方法:GET/POST/PUT/DELETE</param>
/// <param name="jsonData">返回的json数据</param>
/// <param name="errMsg">错误信息</param>
/// <returns>true:成功 false:失败</returns>
public static bool RequestHttpData(string url, string paraJson, string requestMethod, out string jsonData, out string errMsg)
{
jsonData = string.Empty;
errMsg = string.Empty;
string result = string.Empty;
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 15 * 60 * 1000; //15分钟
request.Method = requestMethod;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.ContentType = "application/json";
byte[] postdatabtyes = Encoding.UTF8.GetBytes(paraJson);
request.ContentLength = postdatabtyes.Length;
Stream requeststream = request.GetRequestStream();
requeststream.Write(postdatabtyes, 0, postdatabtyes.Length);
requeststream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd();
} }
catch (WebException ex)
{
try
{
WebResponse wr = ex.Response;
Stream st = wr.GetResponseStream();
StreamReader sr = new StreamReader(st, System.Text.Encoding.Default);
string tmpErr = sr.ReadToEnd();
Regex r = new Regex(@"\<body\>\<h1\>.*\</h1\>");
errMsg = r.Match(tmpErr).Value.Replace("<body><h1>", "").Replace("</h1>", "");
sr.Close();
st.Close();
}
catch
{
errMsg = ex.Message;
}
return false;
}
catch (Exception ex)
{
errMsg = ex.Message;
return false;
}
if (!string.IsNullOrWhiteSpace(result))
{
jsonData = result;
}
return true;
}