Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

httpwebrequest - How to pass POST parameters to ASP.Net web request?

I'm trying to make web requests programmatically in ASP.NET, using the POST method.
I'd like to send POST parameters with the web request as well. Something like this:

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");

obviously the commented line does not work. How do I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try like this...

  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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...