在C/S架构下的winform项目有时候会使用到WEBAPI的接口,需要在winform中模拟HTTP请求获取数据等操作。
截取部分示例代码做解释
//按钮事件,弹窗提示返回内容
private void button2_Click(object sender, EventArgs e)
{
string httpResponse = string.Empty;
string url = "http://127.0.0.1/K3API/Token/Create?authorityCode=d947613eec0ad8f583e3e7946cac0db0a9735393b7e6e76f";
bool flag = HttpHelper.HttpGet(url, out httpResponse, 6000);
MessageBox.Show(httpResponse);
}
//httphelper中的方法
//Get请求
public static bool HttpGet(string url, out string HttpWebResponseString, int timeout)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebResponseString = "";
bool result;
try
{
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
httpWebRequest.Method = "GET";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.UserAgent = HttpHelper.DefaultUserAgent;
httpWebRequest.Timeout = timeout;
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
HttpWebResponseString = HttpHelper.ReadHttpWebResponse(httpWebResponse);
result = true;
}
catch (Exception ex)
{
HttpWebResponseString = ex.ToString();
result = false;
}
return result;
}
//post 请求
public static bool HttpPost(string url, byte[] Data, out string HttpWebResponseString, int timeout)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebResponseString = "";
Stream stream = null;
bool result;
try
{
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.UserAgent = HttpHelper.DefaultUserAgent;
httpWebRequest.Timeout = timeout;
if (Data != null)
{
HttpHelper.requestEncoding.GetString(Data);
stream = httpWebRequest.GetRequestStream();
stream.Write(Data, 0, Data.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
HttpWebResponseString = HttpHelper.ReadHttpWebResponse(httpWebResponse);
result = true;
}
catch (Exception ex)
{
HttpWebResponseString = ex.ToString();
result = false;
}
finally
{
if (stream != null)
{
stream.Close();
}
}
return result;
}
//文本解析
public static string ReadHttpWebResponse(HttpWebResponse HttpWebResponse)
{
Stream stream = null;
StreamReader streamReader = null;
string result = null;
try
{
stream = HttpWebResponse.GetResponseStream();
streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
result = streamReader.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
if (stream != null)
{
stream.Close();
}
if (HttpWebResponse != null)
{
HttpWebResponse.Close();
}
}
return result;
}