我试图编写一个C#脚本,它实际上与我通过某个网页的UI提交表单时的行为相同。这是在不使用Cookie的网站的公共页面上。我在“网络”标签中查看了Chrome,以了解我在提交评论时在请求/响应中发生的情况
我试图在C#land中模仿它:
CommentFormData data = CommentFormData.GenerateRandom();
string json = new JavaScriptSerializer().Serialize(data);
StringContent content = new StringContent(json, Encoding.UTF8);
content.Headers.TryAddWithoutValidation("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
content.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
content.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.8");
content.Headers.TryAddWithoutValidation("Connection", ";eep-alive");
content.Headers.TryAddWithoutValidation("Content-Length", json.Length.ToString());
content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
content.Headers.TryAddWithoutValidation("Host", "...");
content.Headers.TryAddWithoutValidation("Origin", "...");
content.Headers.TryAddWithoutValidation("Referer", "...);
content.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
content.Headers.TryAddWithoutValidation("X-Prototype-Version", "1.6.1");
content.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
HttpResponseMessage response = await client.PostAsync("...", content);
.....
internal class CommentFormData
{
public string pageID { get; } = "...";
public string comment { get; set; }
public string author { get; set; }
public string email { get; set; }
public int timezone { get; } = -7;
public static CommentFormData GenerateRandom()
{
return new CommentFormData()
{
comment = GenerateRandomString(),
author = GenerateRandomString(),
email = $"{GenerateRandomString()}@gmail.com"
};
}
private static string GenerateRandomString(int length = 100)
{
Random random = new Random();
return new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
}
我正在取回状态代码200,但它的工作方式不同。我得到的回应是
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: keep-alive
Keep-Alive: timeout=20
Vary: Accept-Encoding
Date: Sat, 10 Jun 2017 20:44:36 GMT
Server: nginx
Content-Type: text/xml; charset=utf-8
}
那为什么这不起作用?有什么想法吗?
答案 0 :(得分:0)
我认为您应该查看System.Net.Http.HttpsClient类:https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx
使用此calss异步构造和执行请求,并读取其响应的内容。