用.NET C# 发送HTTP 请求,返回结果

来源:互联网 发布:我要买微信木马软件 编辑:程序博客网 时间:2024/04/28 04:14

1、方法一

  public string SendPostHttp( string Url,string datastr)
  {
   try
   {
    byte[] data = System.Text.Encoding.GetEncoding ("GB2312").GetBytes ( datastr ) ;
    // 准备请求...
    HttpWebRequest req = (HttpWebRequest) WebRequest.Create ( Url ) ; 
    req.Method = "Post" ;  //Get or Post
    req.ContentType ="application/x-www-form-urlencoded";
    req.ContentLength = data.Length ;
    Stream stream = req.GetRequestStream () ;
    // 发送数据
    stream.Write ( data ,0 ,data.Length ) ;
    stream.Close () ;

    HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
    Stream receiveStream = rep.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
    // Pipes the stream to a higher level stream reader with the required encoding format. 
    StreamReader readStream = new StreamReader( receiveStream, encode );

    Char[] read = new Char[256];
    int count = readStream.Read( read, 0, 256 );
    StringBuilder sb = new StringBuilder ("") ;
    while (count > 0) 
    {
     String readstr = new String(read, 0, count);
     sb.Append ( readstr ) ;
     count = readStream.Read(read, 0, 256);
    }

    rep.Close();
    readStream.Close();

    return sb.ToString () ;

   }
   catch(Exception ex)
   {
    return "" ;     
   }
  } 

调用     SendPostHttp( 'http://www.abc.com/abc.php', "?Name=cc&PWD=123")

2、方法二

WebClient c = new WebClient();
   byte[] ret = c.DownloadData("http://www.abc.com/register.php?id=11&account=" + UserName + "&password=" +  UserMd5( UserPwd ) );
   string srcString = Encoding.UTF8.GetString(ret);
   string[] values = srcString.Split(',');
   if (values[0] == "SUCCESS")
    return values[1].ToString();
   else
    return "FAILED";

原创粉丝点击