程序中通过地址访问网页

通过地址访问网页方法:


/// <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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值