/// <summary>
/// 根据webapi地址,获取返回的json数据(GET方式)
/// 作者:
/// </summary>
/// <param name="url">webapi资源地址</param>
/// <returns>返回获取的json数据资源</returns>
public static string GetJsonByWebApi(string url)
{
WebResponse wr_result = null;
StringBuilder txthtml = new StringBuilder();
try
{
WebRequest _wr_req = WebRequest.Create(url);
wr_result = _wr_req.GetResponse();
Stream ReceiveStream = wr_result.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
txthtml.Append(str);
count = sr.Read(read, 0, 256);
}
}
catch (Exception)
{
txthtml.Append("err");
}
finally
{
if (wr_result != null)
{
wr_result.Close();
}
}
return txthtml.ToString();
}
/// <summary>
/// 根据webapi地址,获取返回的json数据(POST方式)
/// param参数(name=1&name2=3...),url:webapi地址(http://***.ashx)
/// 作者:
/// </summary>
/// <param name="param"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string GetJsonByWebApiPost(string url,string param)
{
WebResponse wr_result = null;
StringBuilder txthtml = new StringBuilder();
try
{
byte[] bs = System.Text.Encoding.GetEncoding("utf-8").GetBytes(param);
WebRequest _wr_req = WebRequest.Create(url);
_wr_req.Method = "POST";
_wr_req.ContentType = "application/x-www-form-urlencoded";
_wr_req.ContentLength = bs.Length;
System.IO.Stream RequestStream = _wr_req.GetRequestStream();
RequestStream.Write(bs, 0, bs.Length);
RequestStream.Close();
wr_result = _wr_req.GetResponse();
Stream ReceiveStream = wr_result.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
txthtml.Append(str);
count = sr.Read(read, 0, 256);
}
}
catch (Exception)
{
txthtml.Append("err");
}
finally
{
if (wr_result != null)
{
wr_result.Close();
}
}
return txthtml.ToString();
}