C# Winfrom 中模擬HTTP請求

在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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章