应用HttpWebRequest接收post或get数据

181 篇文章 3 订阅
 

/*接收post数据

      string url=http://liuleiceshi.hexun.com/payment/WebForm1.aspx;

     string stext = HttpRequestFromPost(url, "s=1213213&t=1111");

*/

private string HttpRequestFromPost(string maiurl, string paramurl)
    {
      string strHtmlContent = "";
      HttpWebRequest request;
      try
      {
        Encoding encoding = Encoding.GetEncoding("GB2312");

        //声明一个HttpWebRequest请求
        request = (HttpWebRequest)WebRequest.Create(maiurl);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = true;
        byte[] Postbyte = Encoding.ASCII.GetBytes(paramurl);
        request.ContentLength = Postbyte.Length;

        Stream newStream = request.GetRequestStream();
        newStream.Write(Postbyte, 0, Postbyte.Length);//把参数用流对象写入request对象中  
        newStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获得服务器响应对象 
        Stream resStream = response.GetResponseStream();//转成流对象  
        StreamReader sr = new StreamReader(resStream, encoding);
        strHtmlContent = sr.ReadToEnd();
        response.Close();
      }
      catch (Exception ex)
      {
        help.log("网支中连接接口出现问题,错误信息:"+help.SetErrorInfo(ex.Message));
      }
      finally
      {
        request = null;
      }
      if (strHtmlContent == null)
        strHtmlContent = "";
      return strHtmlContent;
    }

/*

接收get数据

      string url="http://liuleiceshi.hexun.com/payment/WebForm1.aspx";
      string stext = help.GetHtmlContent(url);
*/

    public string GetHtmlContent(string Url)
    {
      string strHtmlContent = "";
      HttpWebRequest request;
      try
      {
        //声明一个HttpWebRequest请求
        request = (HttpWebRequest)WebRequest.Create(Url);
        //连接超时时间
        request.Timeout = 20000;
        request.Headers.Set("Pragma", "no-cache");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream streamHtmlCode = response.GetResponseStream();
        Encoding encoding = Encoding.GetEncoding("GB2312");
        StreamReader streamReader = new StreamReader(streamHtmlCode, encoding);
        strHtmlContent = streamReader.ReadToEnd();
      }
      catch (Exception ex)
      {
        help.log("网支中连接接口出现问题,错误信息:"+SetErrorInfo(ex.Message));
      }
      finally
      {
        request = null;
      }
      if (strHtmlContent == null)
        strHtmlContent = "";
      return strHtmlContent;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值