如何查看HTTPWebRequest响应?

时间:2011-05-24 12:10:11

标签: .net vb.net httpwebrequest

Dim s As HttpWebRequest
Dim username= "username=" + HttpUtility.UrlEncode("username")
Dim message = "message=" + HttpUtility.UrlEncode("message")
Dim sep = "&"
Dim sb As New StringBuilder()
sb.Append(username).Append(sep).Append(message)
s = HttpWebRequest.Create("http://www.website.com/?" + sb.ToString())
s.Method = "GET"
Dim result = s.GetResponse()    

我如何回应。将结果写入屏幕? 我得到类似'System.Net.WebResponse'类型的值的错误无法转换为'String'。

2 个答案:

答案 0 :(得分:0)

s.GetResponse()返回WebResponse,这不是你可以打印的东西。实际响应数据在result.Headers和result.GetResponseStream()中。您需要将数据(您读取任何Stream的方式)读取到字符串中,然后输出到屏幕上。

答案 1 :(得分:0)

听起来你正在创建一个基本代理。您需要做的就像Tridus所说的那样是获取响应流然后将内容从一个写入另一个。我之前在一个可能对你有用的开源项目中做过这个。

Managed Fusion Rewriter Proxy Class

我知道这是C#,但VB中的过程仍然相同。应该看起来像这样:

Using responseStream = response.GetResponseStream()
    Using bufferStream = New BufferedStream(responseStream, Manager.Configuration.Rewriter.Proxy.BufferSize)
        Dim buffer As Byte() = New Byte(bufferSize - 1) {}

        Try
            While True
                ' make sure that the stream can be read from
                If Not bufferStream.CanRead Then
                    Exit While
                End If

                Dim bytesReturned As Integer = bufferStream.Read(buffer, 0, bufferSize)

                ' if not bytes were returned the end of the stream has been reached
                ' and the loop should exit
                If bytesReturned = 0 Then
                    Exit While
                End If

                ' write bytes to the response
                context.Response.OutputStream.Write(buffer, 0, bytesReturned)
            End While
        Catch exc As Exception
            Manager.Log("Error on response: " + exc.Message, "Proxy")
        End Try
    End Using
End Using

请注意,这是我的来源的直接翻译,因此您必须为自己的程序进行自定义。