index.asp代码:
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>新建网页 1</title>
</head><body>
<form id="frmmain" method="post" action="test.asp">
<table>
  <tr>
    <td>
      <input type=text name="un" id="un">      
    </td>
  </tr>
  <tr>  
    <td>
      <input type=password name="pd" id="pd">
    </td>
  </tr>
</table>
<table>
  <tr>
    <td>
      <input type=submit id="ok" value="提交">
    </td>
  </tr>
</table>
</form>
</body></html>winform代码:
//建立登录检查地址
string url = @"http://192.168.1.99"; //建立request对象
System.Net.HttpWebRequest req=(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); //这个新建的Cookie集合不知道有什么用??
//req.CookieContainer =new CookieContainer (); req.Method="POST";//POST方式请求
req.ContentType= "application/x-www-form-urlencoded";//内容类型
//参数经过URL编码
string paraUrlCoded;
paraUrlCoded=System.Web.HttpUtility.UrlEncode("un") +"="+System.Web.HttpUtility.UrlEncode("username");
paraUrlCoded+="&";
paraUrlCoded+=System.Web.HttpUtility.UrlEncode("pd")+"="+System.Web.HttpUtility.UrlEncode("password"); //将URL编码后的字符串转化为字节
try
{
byte[] payload;
payload=System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
req.ContentLength=payload.Length; //设置请求的ContentLength
System.IO.Stream writer=req.GetRequestStream();//获得请求流
writer.Write(payload,0,payload.Length);//将请求参数写入流
writer.Close();//关闭请求流
}
catch
{} //获得响应流
}请大家帮我看看这些代码有问题么,有没有其它更好的办法?谢谢!

解决方案 »

  1.   

    byte[] payload;
    payload=System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
    ------------------------------------------------
    把这句换为下面的,其它的应该没有问题,因为程序和我的一样,但我是没有问题的。
    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    Byte[] payload =  encoding.GetBytes(paraUrlCoded);orByte[] payload =  System.Text.Encoding.GetEncoding("GB2312").GetBytes(paraUrlCoded);
      

  2.   

    提交Html请求并保存身份信息 //创建请求
    HttpWebRequest mRequest = WebRequest.Create("http://www.a.com/Login.aspx") as HttpWebRequest;
    mRequest.Method = "POST";
    mRequest.ContentType = "application/x-www-form-urlencoded";
    mRequest.AllowAutoRedirect = false;
    mRequest.CookieContainer = new CookieContainer();string strPostData = "username=aaa&userpwd=bbb";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strPostData);
    mRequest.ContentLength = buffer.Length;//发送数据
    Stream stream = mRequest.GetRequestStream();
    stream.Write(buffer, 0, buffer.Length);
    stream.Close();//得到响应
    wr = (HttpWebResponse)mRequest.GetResponse();
    CookieCollection cc = mRequest.CookieContainer.GetCookies(mRequest.Address);//读取响应内容
    sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));//关闭
    sr.Close();
    wr.Close();http://iyond.cnblogs.com/archive/2006/03/17/352399.html