使用VB.NET调用RESTful服务

时间:2019-04-07 22:31:55

标签: asp.net vb.net

我正在使用以下代码来调用RESTful服务:

    Public Function InvokeService(ByVal RESTServiceURI As String, ByVal RequestMethod As String, ByVal SOAPAction As String, ByVal HTTPHeaderContentType As String, ByVal HTTPHeaderAccept As String, ByVal RequestData As String, ByVal NetworkCredentialUsername As String, ByVal NetworkCredentialPassword As String) As String

    Dim RESTResponse As String = ""

    Try

        Dim RESTRequest As HttpWebRequest = CType(WebRequest.Create(RESTServiceURI), HttpWebRequest)

        If NetworkCredentialUsername <> "" And NetworkCredentialPassword <> "" Then
            Dim objCredential As New Net.NetworkCredential(NetworkCredentialUsername, NetworkCredentialPassword)
            RESTRequest.Credentials = objCredential
        End If

        RESTRequest.Headers.Add("SOAPAction", SOAPAction)

        RESTRequest.Accept = HTTPHeaderAccept
        RESTRequest.Method = RequestMethod

        If RequestMethod = "POST" Or RequestMethod = "PUT" Then

            RESTRequest.ContentType = HTTPHeaderContentType
            RESTRequest.ContentLength = RequestData.Length

            Using RS As Stream = RESTRequest.GetRequestStream
                Using SW As StreamWriter = New StreamWriter(RS)
                    SW.Write(RequestData)
                End Using
            End Using

        End If

        Using Serviceres As WebResponse = RESTRequest.GetResponse()

            Using rd As StreamReader = New StreamReader(Serviceres.GetResponseStream())
                RESTResponse = rd.ReadToEnd()
            End Using

        End Using

    Catch ex As Exception
        RESTResponse = ex.Message
    End Try

    Return RESTResponse

End Function

但是我不知道是否必须使用以下代码行:

RESTRequest.Headers.Add("SOAPAction", SOAPAction)
RESTRequest.Accept = HTTPHeaderAccept

请帮助,我需要此功能才能调用任何RESTful服务。 调用任何RESTful服务是否需要任何增强?

0 个答案:

没有答案