2012-10-19 39 views
1

我基本上有一些想法如何使用HttpWebRequests,但我很新手。所以我想用Post方法提交以下标记。C#需要HttpWebRequest的一些帮助发布数据

authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D 

它能做什么是点击一个按钮,发送文本“测试测试测试”,这是我从萤火虫得到令牌,当我点击我要的按钮。

回答

1

要使用HTTP POST请求,您可以尝试使用下面的代码发送一些数据:

检查“变种serverResponse”服务器响应。

 string targetUrl = "http://www.url.url"; 

     var postBytes = Encoding.Default.GetBytes(@"authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D"); 

     var httpRequest = (HttpWebRequest)WebRequest.Create(targetUrl); 

     httpRequest.ContentLength = postBytes.Length; 
     httpRequest.Method = "POST"; 

     using (var requestStream = httpRequest.GetRequestStream()) 
      requestStream.Write(postBytes, 0, postBytes.Length); 

     var httpResponse = httpRequest.GetResponse(); 

     using (var responseStream = httpResponse.GetResponseStream()) 
      if (responseStream != null) 
       using (var responseStreamReader = new StreamReader(responseStream)) 
       { 
        var serverResponse = responseStreamReader.ReadToEnd(); 
       } 
+0

在线 使用(VAR requestStream = httpRequest.GetRequestStream()) 我得到这个错误:无法发送内容体与这个动词型。 – ISeeSounds

+0

我的不好,我忘了设置httpRequest.Method POST,看到更新后的代码。 – animaonline

+0

得到它的工作,谢谢我的男人 – ISeeSounds

1

又一解决方案:

// you can get the correct encoding from your site's response headers 
Encoding encoding = Encoding.UTF8; 
string targetUrl = "http://example.com"; 
var request = (HttpWebRequest)WebRequest.Create(targetUrl); 

var formData = new Dictionary<string, object>(); 
formData["authenticity_token"] = "pkhn7pwt3QATOpOAfBERZ+RIJ7oBEqGFpnF0Ir4RtJg="; 
formData["question[question_text]"] = "TEST TEST TEST"; 

bool isFirstField = true; 
StringBuilder query = new StringBuilder(); 
foreach (KeyValuePair<string, object> field in formData) 
{ 
    if (!isFirstField) 
     query.Append("&"); 
    else 
     isFirstField= false; 

    query.AppendFormat("{0}={1}", field.Key, field.Value); 
} 

string urlEncodedQuery = Uri.EscapeDataString(query.ToString()); 
byte[] postData = encoding.GetBytes(urlEncodedQuery); 

request.ContentLength = postData.Length; 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 

using (BinaryWriter bw = new BinaryWriter(request.GetRequestStream())) 
    bw.Write(postData); 

var response = request.GetResponse() as HttpWebResponse; 
// TODO: process response