How to fill forms and submit with Webclient in C#

前端 未结 6 972
忘了有多久
忘了有多久 2020-11-29 03:03

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.

I need to build a WinForm ba

6条回答
  •  渐次进展
    2020-11-29 03:37

    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.

    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).

    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
    

提交回复
热议问题