我試圖將傳統的VB6組件(不是我寫的)更新到.NET平臺。有哪些職位的XML字符串的URL一個功能:將VB6 HTTP請求轉換爲VB.Net 2.0
Function PostToUrl(ByRef psUrl, ByRef psData, Byref psResponseText, ByRef psErrorMsg, ByRef psUsername, ByRef psPassword)
On Error Resume Next
Dim objWinHTTP
PostToUrl = False
psErrorMsg = ""
psResponseText = ""
Dim m_lHTTPREQUEST_SETCREDENTIALS_FOR_SERVER
m_lHTTPREQUEST_SETCREDENTIALS_FOR_SERVER =0
Set objWinHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
objWinHTTP.Open "POST", psUrl
If psUsername <> "" Then
Call objWinHTTP.SetCredentials(psUsername, psPassword, m_lHTTPREQUEST_SETCREDENTIALS_FOR_SERVER)
End If
objWinHTTP.SetRequestHeader "Host", "http://www.xxx.com/CSIHTTP.asp"
objWinHTTP.SetRequestHeader "X-Method", "Submit"
objWinHTTP.SetRequestHeader "Content-Type", "text/xml"
objwinHTTP.setTimeouts 3000, 15000, 15000, 120000
Call objWinHTTP.Send(psData)
' Handle errors '
If Err.Number <> 0 Then
psErrorMsg = Err.Description & " test"
PostToUrl = False
ElseIf objWinHTTP.Status <> 200 AND objWinHTTP.Status <> 202 Then
psErrorMsg = "(" & objWinHTTP.Status & ") " & objWinHTTP.StatusText
PostToUrl = False
Else
psErrorMsg = objWinHTTP.ResponseText & "(" & objWinHTTP.Status & ") " & objWinHTTP.StatusText
PostToUrl = True
End If
Set objWinHTTP = Nothing
End Function
我已經更新了這:
Public Function PostXml(ByVal XML As String) As Boolean
Try
Dim URL As String = My.Settings.NTSPostURL
'TODO: supply username and password! '
Dim Bytes As Byte() = Me.Encoding.GetBytes(XML)
Dim HTTPRequest As HttpWebRequest = DirectCast(WebRequest.Create(Me.PostURL), HttpWebRequest)
Dim Cred As New NetworkCredential("username", "password", "http://www.xxx.com")
With HTTPRequest
.Method = "POST"
.ContentLength = Bytes.Length
.ContentType = "text/xml"
.Credentials = Cred
.Timeout = 120000
.Method = "Submit"
End With
Using RequestStream As Stream = HTTPRequest.GetRequestStream()
RequestStream.Write(Bytes, 0, Bytes.Length)
RequestStream.Close()
End Using
Using Response As HttpWebResponse = DirectCast(HTTPRequest.GetResponse(), HttpWebResponse)
If Response.StatusCode <> HttpStatusCode.OK Then
Dim message As String = [String].Format("POST failed. Received HTTP {0}", Response.StatusCode)
Throw New ApplicationException(message)
End If
End Using
Catch ex As WebException
Dim s As String = ex.Response.ToString() & " " & ex.Status.ToString()
Throw
End Try
End Function
然而,當我運行.NET代碼的服務器返回錯誤「403禁止 - 協議錯誤'就行了: Using Response As HttpWebResponse = DirectCast(HTTPRequest.GetResponse(), HttpWebResponse)
。 VB6代碼運行良好。任何人都可以找出兩者之間可能造成這種差異的任何差異嗎?這是讓我難倒....
它不容易移植那些低質量的東西開始。你確定你不想分析更多功能級別的組件並在.NET中實現新鮮事嗎? – AnthonyWJones 2009-06-02 18:45:21
絕對!我深入研究這個VB6函數的唯一原因是,我無法運行.Net代碼! – Simon 2009-06-03 10:36:38