HttpWebRequest失败了

时间:2014-08-13 19:44:43

标签: vb.net session httpwebrequest

我正在尝试使用REST服务。以下是我的代码。这段代码在家庭网络中运行良好,但在工作中失败。

在工作中,它会正常登录并返回会话ID。但是,使用会话ID的任何进一步调用都会挂起。我帮我错了。任何帮助表示赞赏。

Public Shared Function login(username As String, instancename As String, password As String)
    'Dim handler As New HttpClientHandler()
    'handler.Proxy = New System.Net.WebProxy("proxy-test.com:8080")
    'handler.Proxy.Credentials = CredentialCache.DefaultCredentials
    'handler.UseProxy = True

    'Dim client As New HttpClient(handler)
    Dim client As New HttpClient()

    'Construct the Uri
    Dim uri As String = "https://egrcb.archer.rsa.com/api/core/security/login"
    Dim vUri As New Uri(uri)

    client.BaseAddress = vUri

    'Build the request 
    '-Headers:
    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

    '-Body:
    Dim body As String = "{""InstanceName"":""" + instancename + """,""Username"":""" + username + """,""UserDomain"":"""",""Password"":""" + password + """}"
    Dim content As StringContent = New System.Net.Http.StringContent(body, Encoding.UTF8, "application/json")

    '***CALL THE API***
    Dim response As HttpResponseMessage = client.PostAsync(uri, content).Result
    '******************

    'Some additional logic to process what came back to reuse it for other things - this is
    'fairly crude and simplistic, but you can write classes or add libraries to consume the
    'JSON that is passed back from the API and handle things in a more sophisticated way if you need to
    Dim status As String = response.StatusCode.ToString()
    Dim result As String = response.Content.ReadAsStringAsync().Result
    Dim statusCode As System.Net.HttpStatusCode = response.StatusCode
    Dim codeNumber As Integer = CInt(statusCode)

    'Some simple error catching - in real-world code you would need to build some logic out for these
    If codeNumber <> 200 Then
        Throw New Exception("The request failed for some reason")
    End If

    If result.Contains("RequestedObject"":null") Then
        Throw New Exception("The login failed for some reason")
    End If

    Dim extractedSessionId As String = result.Substring(result.IndexOf("SessionToken"":") + 15, 32)

    Return extractedSessionId
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader
    Dim rawresp As String = ""
    'Login
    Dim sessionid As String = login(txtUserID.Text, txtEnvironmnent.Text, txtPassword.Text)
    txtSessionID.Text = sessionid
    'SOAPlogin()
    lblStatus.Text = "Logged In..."

    Try
        DGVFields.Rows.Clear()
        DGVFields.Columns.Clear()
        lblStatus.Text = "Initiating Connection..."
        request = WebRequest.Create("https://egrcb.archer.rsa.com/api/core/content/2125562")
        request.ContentType = "application/json"
        request.Headers.Add("Authorization", "Archer session-id=""" & txtSessionID.Text & """")
        request.Headers.Add("X-Http-Method-Override", "GET")
        request.Timeout = 6000
        'request.Credentials = CredentialCache.DefaultCredentials
        'Dim proxy As New WebProxy
        'Dim newUri As New Uri("http://proxy-test.com:8080")
        'proxy.Address = newUri
        'proxy.Credentials = CredentialCache.DefaultCredentials
        'request.Proxy = proxy

        lblStatus.Text = "Getting Response..."
        'get repsonse
        response = request.GetResponse()
        'Display
        Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
        'Get the stream content returned
        Dim datastream As Stream = response.GetResponseStream()
        'Open reader
        reader = New StreamReader(datastream)
        lblStatus.Text = "Reading response..."
        Application.DoEvents()
        rawresp = reader.ReadToEnd()
        lblStatus.Text = "Parsing results..."
        Application.DoEvents()
    Catch ex As Exception

    End Try
End sub

1 个答案:

答案 0 :(得分:0)

这里只是一个黑暗的刺,但我假设你的工作有webfilter /代理设置?也许它正在从Web请求中剥离出特定的头文件,或者某些防火墙甚至有一个删除未知的头文件功能,如果标题“X-Http-Method-Override”不在其列表中,那么请求将永远不会响应。我无法解释为什么它会在超时时间内挂起超过6秒。你是否尝试过在工作中调试并逐步完成?

此致

利安