在C# .Net 2005中,与VB6中的XMLHTTP等价的是什么?

3

我正在尝试将一些在VB中很好运行的代码转换到.Net,但是我无法确定要使用哪些对象。

    Dim oXMLHttp As XMLHTTP
    oXMLHttp = New XMLHTTP
    oXMLHttp.open "POST", "https://www.server.com/path", False
    oXMLHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    oXMLHttp.send requestString 

基本上,我希望将一个XML文件发送到服务器,并存储它返回的响应。有人能指点我吗?


被接受的答案不是C#,如果你正在将VB6移植到VB.NET,并希望尽可能地保留你的代码库,那么请重新标记为VB.NET。 - AnthonyWJones
请尝试此链接: https://dev59.com/iVfUa4cB1Zd3GeqPH2xe#10818080 - Abhishek.Chopra
2个回答

3
答案是使用WebClient类:-
WebClient webClient = new WebClient();

NameValueCollection values = new NameValueCollection();

values.add("firstname", "Slarti");
values.add("lastname", "Bart-fast");

byte[] response = webClient.UploadValues("http://server/path", values);

UploadValues方法构建了一个POST请求,其内容类型为application/x-www-form-urlencoded,并正确地对传递给它的NameValueCollection中列出的值进行编码。
响应是一个字节数组,您可以根据需要进行处理。

1
请参考以下示例:http://www.codeproject.com/KB/dotnet/NET_Interact_j2EE.aspx。我已经放置了下面的示例。很抱歉,我知道它很大,但你永远不知道这样的链接会保持多久有效。注意:问题的第一个版本没有说明是在C# .NET中 - 它只是说“在.NET中”。(也许它被标记为C#,但我没有看到)从VB.NET转换到C#非常容易(尽管不必要)。'此类代表MSXML.XMLHTTP中xmlHTTP对象的相同功能。
Imports System.Net
Imports System.Web.HttpUtility

Public Class XMLHTTP
'Makes an internet connection to specified URL 
   Public Overridable Sub open(ByVal bstrMethod As String, _
     ByVal bstrUrl As String, Optional ByVal varAsync As _
     Object = False, Optional ByVal bstrUser _
     As Object = "", Optional ByVal bstrPassword As Object = "")
       Try
           strUrl = bstrUrl
           strMethod = bstrMethod

           'Checking if proxy configuration 
           'is required...(blnIsProxy value 
           'from config file)
           If blnIsProxy Then
           'Set the proxy object
               proxyObject = WebProxy.GetDefaultProxy()

               'Finding if proxy exists and if so set 
               'the proxy configuration parameters...
               If Not (IsNothing(proxyObject.Address)) Then
                   uriAddress = proxyObject.Address
                   If Not (IsNothing(uriAddress)) Then
                       _ProxyName = uriAddress.Host
                       _ProxyPort = uriAddress.Port
                   End If
                   UpdateProxy()
               End If
               urlWebRequest.Proxy = proxyObject
           End If

           'Make the webRequest...
           urlWebRequest = System.Net.HttpWebRequest.Create(strUrl)
           urlWebRequest.Method = strMethod

           If (strMethod = "POST") Then
               setRequestHeader("Content-Type", _
                   "application/x-www-form-urlencoded")
           End If

           'Add the cookie values of jessionid of weblogic 
           'and PH-Session value of webseal 
           'for retaining the same session
           urlWebRequest.Headers.Add("Cookie", str_g_cookieval)

       Catch exp As Exception
           SetErrStatusText("Error opening method level url connection")
       End Try
   End Sub
   'Sends the request with post parameters...
   Public Overridable Sub Send(Optional ByVal objBody As Object = "")
       Try
           Dim rspResult As System.Net.HttpWebResponse
           Dim strmRequestStream As System.IO.Stream
           Dim strmReceiveStream As System.IO.Stream
           Dim encode As System.Text.Encoding
           Dim sr As System.IO.StreamReader
           Dim bytBytes() As Byte
           Dim UrlEncoded As New System.Text.StringBuilder
           Dim reserved() As Char = {ChrW(63), ChrW(61), ChrW(38)}
           urlWebRequest.Expect = Nothing
           If (strMethod = "POST") Then
               If objBody <> Nothing Then
                   Dim intICounter As Integer = 0
                   Dim intJCounter As Integer = 0
                   While intICounter < objBody.Length
                     intJCounter = _
                       objBody.IndexOfAny(reserved, intICounter)
                     If intJCounter = -1 Then
UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _
                                                    objBody.Length - intICounter)))
                       Exit While
                     End If
UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _
                                                        intJCounter - intICounter)))
                     UrlEncoded.Append(objBody.Substring(intJCounter, 1))
                     intICounter = intJCounter + 1
                   End While

                   bytBytes = _
                     System.Text.Encoding.UTF8.GetBytes(UrlEncoded.ToString())
                   urlWebRequest.ContentLength = bytBytes.Length
                   strmRequestStream = urlWebRequest.GetRequestStream
                   strmRequestStream.Write(bytBytes, 0, bytBytes.Length)
                   strmRequestStream.Close()
                Else
                    urlWebRequest.ContentLength = 0
               End If
           End If
           rspResult = urlWebRequest.GetResponse()
           strmReceiveStream = rspResult.GetResponseStream()
           encode = System.Text.Encoding.GetEncoding("utf-8")
           sr = New System.IO.StreamReader(strmReceiveStream, encode)

           Dim read(256) As Char
           Dim count As Integer = sr.Read(read, 0, 256)
           Do While count > 0
               Dim str As String = New String(read, 0, count)
               strResponseText = strResponseText & str
               count = sr.Read(read, 0, 256)
           Loop
       Catch exp As Exception
           SetErrStatusText("Error while sending parameters")
           WritetoLog(exp.ToString)
       End Try
   End Sub
   'Setting header values...
   Public Overridable Sub setRequestHeader(ByVal bstrHeader _
                         As String, ByVal bstrValue As String)
       Select Case bstrHeader
            Case "Referer"
                urlWebRequest.Referer = bstrValue
            Case "User-Agent"
                urlWebRequest.UserAgent = bstrValue
            Case "Content-Type"
                urlWebRequest.ContentType = bstrValue
            Case Else
                urlWebRequest.Headers(bstrHeader) = bstrValue
       End Select
   End Sub

   Private Function UpdateProxy()
       Try
           If Not (IsNothing(uriAddress)) Then
               If ((Not IsNothing(_ProxyName)) And _
                 (_ProxyName.Length > 0) And (_ProxyPort > 0)) Then
                   proxyObject = New WebProxy(_ProxyName, _ProxyPort)
                   Dim strByPass() As String = Split(strByPassList, "|")
                   If strByPass.Length > 0 Then
                       proxyObject.BypassList = strByPass
                   End If
                   proxyObject.BypassProxyOnLocal = True
                   If blnNetworkCredentials Then
                       If strDomain <> "" Then
                           proxyObject.Credentials = New _
                             NetworkCredential(strUserName, _
                             strPwd, strDomain)
                       Else
                            proxyObject.Credentials = New _
                              NetworkCredential(strUserName, _
                              strPwd)
                       End If
                   End If
               End If
           End If
       Catch exp As Exception
           SetErrStatusText("Error while updating proxy configurations")
           WritetoLog(exp.ToString)
       End Try
   End Function
   'Property for setting the Responsetext
   Public Overridable ReadOnly Property ResponseText() As String
       Get
           ResponseText = strResponseText
       End Get
   End Property

   Private urlWebRequest As System.Net.HttpWebRequest
   Private urlWebResponse As System.Net.HttpWebResponse
   Private strResponseText As String
   Private strUrl As String
   Private strMethod As String
   Private proxyObject As WebProxy
   Private intCount As Integer
   Private uriAddress As Uri
   Private _ProxyName As String
   Private _ProxyPort As Integer
End Class

一个由丹·阿普尔曼定制的谷歌搜索! - Booji Boy
也许你应该将上面的代码移植到C#中,以匹配问题要求在C#中寻找等价代码。 - AnthonyWJones
我认为第一个版本的问题没有说清楚是使用C#还是其他语言,它只提到了“.NET”。 - Booji Boy
我必须从VB6迁移到C#,因为我所有个人旧代码都是用VB6编写的,但是我们在我的新工作中使用C#。因此,我不想将旧的方法论带入到.Net中,但是又不想花费8个小时来进行可以在1个小时内完成的转换。 - Matt Dawdy
有没有相应的“getAllResponseHeaders()”函数? - Brain2000
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接