Get函数及Post函数

/// <summary>
/// Get函数
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string GetHttp(string url)
{
string content = "";
try
{
System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
content = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return content;
}

 

 


/// <summary>
/// Post函数
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string PostHttp(string url, string body)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 20000;

byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();

httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();

return responseContent;
}

posted @ 2017-06-21 11:34  突破零  阅读(452)  评论(0编辑  收藏  举报