2012-04-21 107 views
21

我正在嘗試使用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"); 

很明顯,註釋行不起作用。我如何實現這一目標?

回答

53

嘗試像這樣...

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

嗨。感謝您的回覆,除了我沒有收到任何回覆外,一切都很完美。沒有任何內容被打印到頁面上。 – jzeus 2012-04-22 01:48:17

+0

好吧,我可能只是添加一個Response.write()解決了這個問題! – jzeus 2012-04-22 02:12:56

+0

@ V0R73X:你的意思是「responseData.Write()」? – 2014-02-24 23:16:40

相關問題