通过地址访问网页方法:
/// <summary>
/// 同步请求
/// </summary>
/// <param name="sUrl">页面地址</param>
/// <param name="sData">传送数据字符串</param>
/// <param name="sEncode">编码名称(GB2312,UTF-8...)</param>
/// <param name="sUserAgent">UserAgent值</param>
/// <param name="headers">头字段集合</param>
/// <returns></returns>
public static string SyncRequest(string sUrl, string sData, string sEncode, string sUserAgent, Dictionary<string, string> headers)
{
string results = string.Empty;
HttpWebRequest req = null;
HttpWebResponse res = null;
Stream reqStream = null;
StreamReader resStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(sUrl);
if (!string.IsNullOrEmpty(sUserAgent))
{
req.UserAgent = sUserAgent;
}
if (null != headers && headers.Count > 0)
{
foreach (var header in headers)
{
req.Headers.Add(header.Key, header.Value);
}
}
if (!string.IsNullOrEmpty(sData))
{
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
Encoding encoding = Encoding.GetEncoding(sEncode);
byte[] Bytes = encoding.GetBytes(sData);
req.ContentLength = Bytes.Length;
reqStream = req.GetRequestStream();
reqStream.Write(Bytes, 0, Bytes.Length);
}
res = (HttpWebResponse)req.GetResponse();
resStream = new StreamReader(res.GetResponseStream());
results = resStream.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (null != resStream)
{
resStream.Close();
}
if (null != reqStream)
{
reqStream.Close();
}
}
return results;
}
调用方法:
配置文件中的调用地址:<add key="URL" value="http://172.18.8.122:8085/GetEMPToken.ashx"/>
string url = ConfigurationManager.AppSettings["URL"];
SyncRequest(url, null, "utf-8", "", null);