如何保存会话,以便我们在使用REST服务时不必再次登录

时间:2019-07-01 13:07:26

标签: vb.net

我是VB.net的新手(从今天开始),我想使用某些服务器上的REST服务。问题是,首先我们需要使用一些URL登录到服务器,然后才能触发一些查询。但是,如果第二个查询给出401错误,则登录部分工作正常。因此,如果发现我的请求是未经授权的。 现在我不知道如何在步骤1之后保存登录信息,即使用用户名和密码登录。 这样我就可以使用同一登录名来触发使用同一登录名的不同查询

我在下面尝试了一些代码

Public Shared Function queryResult(xhttp As System.Net.HttpWebRequest, query As String)
        Try
            Dim fr = xhttp
            Dim targetURI As New Uri(query)
 '"http://localhost:8682/servlet/rest/query?type=login&user="test"&pass="test"
            Dim Req = HttpWebRequest.Create(targetURI)

            fr = DirectCast(Req, System.Net.HttpWebRequest)

            'fr.KeepAlive = True
            'fr.Connection = True
            Dim response = DirectCast(fr.GetResponse(), HttpWebResponse)
            Console.WriteLine(response)
            fr.PreAuthenticate = True
            If (response.StatusCode = HttpStatusCode.OK) Then
                Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
                Console.WriteLine(str.ReadToEnd)

            End If


            response.Close()

            targetURI = New Uri("http://localhost:8682/servlet/rest/query?type=Model&expr=%5B%5D")
            fr.PreAuthenticate = True

            Req = HttpWebRequest.Create(targetURI)

            response = DirectCast(Req.GetResponse(), HttpWebResponse)
            Console.WriteLine(response)
            If (response.ContentLength > 0) Then
                Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
                Console.WriteLine(str)

            End If
        Catch ex As System.Net.WebException
            Console.WriteLine(ex)

        End Try

--------------------------Output---------------------------
"**first login workes fine**"

System.Net.HttpWebResponse
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='login.xsl'?>
<login success="true" version="1.9"/>

"**but the second query shows the following error**"

System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at Project2.RestUtilForQuery.queryResult(HttpWebRequest xhttp, String query)

0 个答案:

没有答案