VB net HTTP请求原生

Shared Function AllHttpRequest(ByVal url As String, ByVal verb As String, ByVal postVars As String) As ResultDto
        Dim resultDto As ResultDto = New ResultDto
        Dim result As String = Nothing
        Try
            Dim req As HttpWebRequest = TryCast(WebRequest.Create(New Uri(url)), HttpWebRequest)
            req.Method = verb
            req.ContentType = "application/json; charset=UTF-8"
            req.Accept = "application/json; charset=UTF-8"
            req.Headers.Add(String.Format("Authorization: Bearer {0}", AccessToken))
            'OrElse (verb.Equals("GET"))
            If (verb.Equals("POST")) OrElse (verb.Equals("PUT")) Then
                Dim content As Byte() = Encoding.UTF8.GetBytes(postVars)
                req.ContentLength = content.Length
                Using post As Stream = req.GetRequestStream()
                    post.Write(content, 0, content.Length)
                End Using
            End If
            Using resp As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
                Dim reader As New StreamReader(resp.GetResponseStream())
                result = reader.ReadToEnd()
                reader.Close()
                resultDto.data = result
            End Using
        Catch [error] As WebException

            resultDto.result = False

            If DirectCast([error].Response, System.Net.HttpWebResponse).StatusDescription = "Forbidden" Then
                resultDto.message = "访问权限限制 无法访问!"
                Return resultDto
            Else

            End If

            If [error].Status = WebExceptionStatus.ProtocolError Then
                Dim reader As New StreamReader([error].Response.GetResponseStream())
                result = reader.ReadToEnd()
                reader.Close()
                resultDto.message = Http.DisposeError(result)
                Return resultDto
            End If
            resultDto.message = [error].Message
        End Try
        Return resultDto
    End Function

 

posted @ 2020-04-30 11:39  上帝视角  阅读(703)  评论(1编辑  收藏  举报