在 WinForm 中打开页面采用POST方式传参http。可以多个参数传递,返回json字符串...

//调用方法

Dictionary< string string > postData =  new  Dictionary< string string >();
postData.Add( "user" "aaa" );
postData.Add( "pass" "bbb" );
 
GetPageByPost( "http://www.xxx.com/send.aspx" , postData, Encoding.UTF8);
 
/// <summary>
/// 以 Post 方式提交网页数据,获得服务器返回的数据
/// </summary>
/// <param name="url"> Url </param>
/// <param name="postData">Post 数据</param>
/// <param name="encoder">网页编码</param>
/// <returns>服务器返回的数据</returns>
public  string  GetPageByPost( string  url, Dictionary< string string > postData, Encoding encoder)
{
     string  html =  "" ;
 
     HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
     webReq.Method =  "POST" ;
 
     Stream reqStream =  null ;
     if  (postData !=  null  && postData.Count > 0) {
         StringBuilder sb =  new  StringBuilder();
         foreach  (KeyValuePair< string string > kv  in  postData) {
             sb.Append(HttpUtility.UrlEncode(kv.Key));
             sb.Append( "=" );
             sb.Append(HttpUtility.UrlEncode(kv.Value));
             sb.Append( "&" );
         }
 
         byte [] data = Encoding.UTF8.GetBytes(sb.ToString().TrimEnd( '&' ));
 
         webReq.ContentType = ContentType;
         webReq.ContentLength = data.Length;
         reqStream = webReq.GetRequestStream();
         reqStream.Write(data, 0, data.Length);
     }
 
     HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
     Stream stream = webResp.GetResponseStream();
     StreamReader sr =  new  StreamReader(stream, encoder);
     html = sr.ReadToEnd();
 
     sr.Close();
     stream.Close();
 
     if  (reqStream !=  null ) {
         reqStream.Close();
     }
 
     return  html;
}

转载于:https://www.cnblogs.com/luoqin520/p/4645431.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值