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

时间:2009-04-27 14:29:37

标签: c# webclient

我很擅长在C#中使用库WebClient,HttpResponse和HttpRequest,所以请耐心等待,如果我的问题让人难以理解。

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

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

到目前为止,真好!现在我想填写一个带有数字的表单,然后我从网站上找到源代码,并发现名称是“数字”。所以我写这个:

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

但我该怎么提交呢?我希望收到我的“搜索结果”...

6 个答案:

答案 0 :(得分:48)

您可能应该使用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();

答案 1 :(得分:37)

试试这个:

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 = Encoding.UTF8.GetString(result);
}

答案 2 :(得分:3)

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

我解决了它从头开始生成POST数据并打开包含在表单操作中的uri。

答案 3 :(得分:1)

使用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();
}

答案 4 :(得分:0)

您已使用UploadValues提交了该文件。问题是:你的“结果搜索”是什么?页面返回什么? HTML?如果是这样 - HTML Agility Pack是解析html的最简单方法。

答案 5 :(得分:0)

BFree的回答很有效。但有一点我要注意的是,数据连接应该是url编码的,否则你会遇到像“=”和“&amp;”这样的问题。数据中的标志。

下面是支持urlencoded和UTF-8的VB.NET版本(请注意,url-encoding需要引用System.Web.dll,这在我从.NET 4 Compact Framework切换到之后才对我有用。常规的.NET 4 Framework。)

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