如何将POST参数传递给ASP.Net Web请求?
问题描述:
我正在尝试使用POST方法在ASP.NET中以编程方式发出Web请求。
我想用web请求发送POST参数。类似这样的:如何将POST参数传递给ASP.Net Web请求?
WebRequest req = WebRequest.Create("accounts.craigslist.org/login/pstrdr");
req.Method = "POST";
req.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
//WebRequest.Parameters.add("areaabb","hou");
很明显,注释行不起作用。我如何实现这一目标?
答
尝试像这样...
string email = "YOUR EMAIL";
string password = "YOUR PASSWORD";
string URLAuth = "https://accounts.craigslist.org/login";
string postString = string.Format("inputEmailHandle={0}&name={1}&inputPassword={2}", email, password);
const string contentType = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.Expect100Continue = false;
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = contentType;
webRequest.CookieContainer = cookies;
webRequest.ContentLength = postString.Length;
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webRequest.Referer = "https://accounts.craigslist.org";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
webRequest.GetResponse().Close();
嗨。感谢您的回复,除了我没有收到任何回复外,一切都很完美。没有任何内容被打印到页面上。 – jzeus 2012-04-22 01:48:17
好吧,我可能只是添加一个Response.write()解决了这个问题! – jzeus 2012-04-22 02:12:56
@ V0R73X:你的意思是“responseData.Write()”? – 2014-02-24 23:16:40