1

我基本上知道如何使用 HttpWebRequests,但我还是个新手。所以我想用 Post 方法提交以下令牌。

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

它的作用是单击一个按钮并发送文本“TEST TEST TEST”,这是我单击我想要的按钮时从萤火虫获得的令牌。

4

2 回答 2

1

要使用 Http Post Request 发送一些数据,您可以尝试使用以下代码:

检查“var 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();
                }
于 2012-10-19T11:19:33.543 回答
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
于 2012-10-19T11:48:19.413 回答