如何在 C# 中填写表单并使用 Webclient 提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/793755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:25:11  来源:igfitidea点击:

How to fill forms and submit with Webclient in C#

c#webclient

提问by

I'm new at using the the libraries WebClient, HttpResponse and HttpRequest in C#, so bear with me, if my question is confusing to read.

我是在 C# 中使用 WebClient、HttpResponse 和 HttpRequest 库的新手,如果我的问题难以阅读,请耐心等待。

I need to build a WinForm based on C# which can open a URL, which is secured with the basic authorization. I did this with adding this to the header, like this:

我需要基于 C# 构建一个可以打开 URL 的 WinForm,该 URL 受基本授权保护。我通过将其添加到标题中来做到这一点,如下所示:

using (WebClient wc = new WebClient())
{
    wc.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
    Convert.ToBase64String(
    Encoding.ASCII.GetBytes(username + ":" + password)));
}

So far, so good! Now I would like to fill a form with a number, and I find the source-code from the site, and discover that the name is "number". So I write this:

到现在为止还挺好!现在我想用一个数字填写一个表格,我从网站上找到源代码,发现名字是“数字”。所以我写这个:

NameValueCollection formData = new NameValueCollection();  
formData["number"] = number
byte[] responseBytes = wc.UploadValues(theurl, "POST", formData);
string response = Encoding.ASCII.GetString(responseBytes);
textBox_HTML.Text = response; 

But how do I submit this? I will like to receive my "search-results"...

但是我该如何提交呢?我想收到我的“搜索结果”...

回答by BFree

You should probably be using HttpWebRequestfor this. Here's a simple example:

您可能应该HttpWebRequest为此使用。这是一个简单的例子:

var strId = UserId_TextBox.Text;
var strName = Name_TextBox.Text;

var encoding=new ASCIIEncoding();
var postData="userid="+strId;
postData += ("&username="+strName);
byte[]  data = encoding.GetBytes(postData);

var myRequest =
  (HttpWebRequest)WebRequest.Create("http://localhost/MyIdentity/Default.aspx");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
var newStream=myRequest.GetRequestStream();
newStream.Write(data,0,data.Length);
newStream.Close();

var response = myRequest.GetResponse();
var responseStream = response.GetResponseStream();
var responseReader = new StreamReader(responseStream);
var result = responseReader.ReadToEnd();

responseReader.Close();
response.Close();

回答by Marc Gravell

You submitted it already with UploadValues. The question is: what is your "result-search"? What does the page return? HTML? If so - the HTML Agility Packis the easiest way to parse html.

你已经用UploadValues. 问题是:你的“结果搜索”是什么?页面返回什么?HTML?如果是这样 - HTML Agility Pack是解析 html 的最简单方。

回答by Marc Gravell

I have found a solution to my problem. First of all I was confused about some of the basics in http-communication. This was caused by a python-script i wrote, which have a different approach with the communication.

我已经找到了解决我的问题的方。首先,我对 http 通信中的一些基础知识感到困惑。这是由我写的一个 python 脚本引起的,它有不同的通信方。

I solved it with generating the POST-data from scratch and open the uri, which was contained in the form-action.

我通过从头开始生成 POST 数据并打开包含在表单操作中的 uri 解决了这个问题。

回答by Michael Zlatkovsky - Microsoft

BFree's answer works great. One thing I would note, though, is that the data concatenation should really be url-encoded, otherwise you'd have trouble with things like "=" and "&" signs within the data.

BFree 的回答效果很好。不过,我要注意的一件事是,数据连接确实应该是 url 编码的,否则您会在数据中遇到诸如“=”和“&”符号之类的问题。

The VB.NET version, urlencoded and with UTF-8 support, is below (note that url-encoding requires a reference to System.Web.dll, which only worked for me after I switched from .NET 4 Compact Framework to the regular .NET 4 Framework).

VB.NET 版本、urlencoded 和 UTF-8 支持如下(请注意,url 编码需要对 System.Web.dll 的引用,它仅在我从 .NET 4 Compact Framework 切换到常规 . NET 4 框架)。

Imports System.Web
Imports System.Net
Imports System.IO

Public Class WebFormSubmitter

    Public Shared Function submit(ByVal address As String,
                                  ByVal values As Dictionary(Of String, String)) As String
        Dim encoding As New UTF8Encoding
        Dim postData As String = getPostData(values:=values)
        Dim data() As Byte = encoding.GetBytes(postData)

        Dim request = CType(WebRequest.Create(address), HttpWebRequest)
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = data.Length
        Dim newStream = request.GetRequestStream()
        newStream.Write(data, 0, data.Length)
        newStream.Close()

        Dim response = request.GetResponse()
        Dim responseStream = response.GetResponseStream()
        Dim responseReader = New StreamReader(responseStream)
        Return responseReader.ReadToEnd()
    End Function

    Private Shared Function getPostData(ByVal values As Dictionary(Of String, String)) As String
        Dim postDataPairList As New List(Of String)
        For Each anEntry In values
            postDataPairList.Add(anEntry.Key & "=" & HttpUtility.UrlEncode(anEntry.Value))
        Next
        Return String.Join(separator:="&", values:=postDataPairList)
    End Function

End Class

回答by mrlingam

Try this:

尝试这个:

using System.Net;
using System.Collections.Specialized;  

NameValueCollection values = new NameValueCollection();
values.Add("TextBox1", "value1");
values.Add("TextBox2", "value2");
values.Add("TextBox3", "value3");
string Url = urlvalue.ToLower();

using (WebClient client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    byte[] result = client.UploadValues(Url, "POST", values);
    string ResultAuthTicket = System.Text.Encoding.UTF8.GetString(result);
}

回答by user3285954

Posting a form with System.Net.Http.HttpClient and reading the response as string:

使用 System.Net.Http.HttpClient 发布表单并将响应读取为字符串:

var formData = new Dictionary<string, string>();
formData.Add("number", number);

var content = new FormUrlEncodedContent(formData);

using (var httpClient = new HttpClient())
{
    var httpResponse = await httpClient.PostAsync(theurl, content);

    var responseString = await httpResponse.Content.ReadAsStringAsync();
}