美文网首页
ASP.NET-接口-发送请求

ASP.NET-接口-发送请求

作者: 柠檬正在努力 | 来源:发表于2020-06-11 09:27 被阅读0次

直接上代码,此处语言是VB.NET,使用者自行更改语法,核心功能已经注释

/*
''' <summary>
''' 发送Post请求,获取数据
''' </summary>
''' <param name="url">请求地址</param>
''' <param name="data">请求数据</param>
''' <returns></returns>
*/
Private Shared Function PostData(ByVal url As String, ByVal data As String) As String
    ServicePointManager.Expect100Continue = False
    Dim request As HttpWebRequest = WebRequest.Create(url)
    /*Post请求方式 */ 
    request.Method = "POST"
    /*内容类型  */
    request.ContentType = "application/json"
    /*不在请求中包含一个Expect:100-continue并询问Server使用愿意接受数据*/
    request.ServicePoint.Expect100Continue = False
    /*将URL编码后的字符串转化为字节  */
    Dim encoding As New UTF8Encoding()
    Dim bys As Byte() = encoding.GetBytes(data)
    /*设置请求的ContentLength   */
    request.ContentLength = bys.Length
    /*获得请求流  */
    Dim newStream As Stream = request.GetRequestStream()
    newStream.Write(bys, 0, bys.Length)
    newStream.Close()
    /*获得响应流  */
    Dim sr As StreamReader = New StreamReader(request.GetResponse().GetResponseStream)
    Return sr.ReadToEnd
End Function

对于Data此处可以采用dictionary构造params的方式
Dim params = New Dictionary(Of String, String)
params.Add("param", "flow= token,appKey=" & authAppKey)
params.Add("data", token)
然后再进行调用函数即可
Dim strHtml As String = PostData(authUrl, params)


下面是Get请求实例,其实大同小异

Private Function GetUserReInfo(ByRef reurl As String, ByRef token As String) As Boolean
    Try
        Dim IID As Integer = 0
        Dim myRequest As Net.HttpWebRequest = Net.WebRequest.Create(reurl)
        myRequest.Method = "Get"
        myRequest.Headers.Add("AppToken",  token)
        myRequest.Accept = "application/json"
        myRequest.ContentType = "application/json; charset=utf-8"
        Dim response As WebResponse = myRequest.GetResponse()
        Dim reader As StreamReader = New StreamReader(response.GetResponseStream(), Encoding.UTF8)
        Dim strHtml As String = reader.ReadToEnd()
        reader.Close()
        Return True
    Catch ex As Exception
        ExMessage = ex.Message
        Return False
    End Try
End Function

相关文章

网友评论

      本文标题:ASP.NET-接口-发送请求

      本文链接:https://www.haomeiwen.com/subject/urpvtktx.html