前些天有個要求要從某個網站上取資訊,但是該網站要求用post方式訪問的.現在這裡貼兩個google到的方法.
using System.Net;
static string WebClinetPost(string url, string postData, string encodeType,out string err)
{
string uriString = url;
byte[] byteArray;
byte[] responseArray;
//postData = "checkvalue=32&bbb=%CD%B6%C6%B1&ilc=0&kkk=22";
Encoding encoding = Encoding.GetEncoding(encodeType);
try
{
WebClient myWebClient = new WebClient();
WebHeaderCollection myWebHeaderCollection;
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
//myWebClient.Headers.Add("Referer"," http://xxxxx/xxxxxxxxxxxxxxxxxxxxxxxx
//myWebClient.Headers.Add("Accept-Language","zh-cn");
myWebHeaderCollection = myWebClient.Headers;
byteArray = encoding.GetBytes(postData);
responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
err=string.Empty;
return encoding.GetString(responseArray);
}
catch(Exception ex)
{
err=ex.Message;
return string.Empty;
}
}
public static string HttpWebResponsePost(string url, string postData,string encodeType,out string err)
{
Stream outstream = null;
Stream instream=
null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.GetEncoding(
encodeType);
byte[] data = encoding];
request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST"; request.ContentType = "appliRedirect
= true;request.Method =
"POST"; request.ContentType-form-urlencoded";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data,0,data.Length);
outstream.Close();
response = request.GetResponse() as HttpWebResrase;
instream = response.GetResponseStream();
sr = new StreamReader( instream, encoding );
string content = sr.ReadToEnd();
err = string.Empty;
return content;
}
catch(Exception ex)
{
err = ex.Message;
return string.Empty;
}
}
呼叫程式碼:
string url=" http://xxxxxx/xxxxxxxx/scrrm00542.jsp ";
string postData="proj_id=600197&theSubmit=600197";
string encodeType="utf-8";
string err="";
//string content=HttpWebResponsePost(url,postData,encodeType,out err);
string content=WebClinetPost(url,postData,encodeType,out err);
另外,再附上javascript實作的程式碼吧:
http://www.cnblogs.com/lwyaster/archive/2007/01/09/615815.html