vb.net 从数据流中获取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22356497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:03:15  来源:igfitidea点击:

Get a string from a data stream

vb.netasp.net-web-apistream

提问by J86

I am accessing an API through a .NET 3.5 application, and so far my code looks like so:

我正在通过 .NET 3.5 应用程序访问 API,到目前为止,我的代码如下所示:

Dim strLink As String = "http://www.google.co.uk"

Dim request As WebRequest = System.Net.WebRequest.Create("http://random-web-api/controller/id")

Dim response As WebResponse = request.GetResponse()

If CType(response,HttpWebResponse).StatusCode = HttpStatusCode.OK Then

    Dim dataStream As Stream = response.GetResponseStream()

    ' How do I get the String from the Stream? 

    response.Close()
End If

I am able to call the API, and get an OK status, but I don't know how to convert my ResponseStreaminto a Stringin VB?

我可以调用 API,并获得 OK 状态,但我不知道如何将我的ResponseStream转换为StringVB 中的 a?

回答by Max

Most easy way I could think of:

我能想到的最简单的方法:

'Convert stream to string
Dim reader As New StreamReader(response.GetResponseStream())
Dim streamText As String = reader.ReadToEnd()

Note: This will only work for ASCII encoding.

注意:这仅适用于 ASCII 编码。

Edit, you could add following method to your application, this one allows a encoding parameter.

编辑,您可以将以下方法添加到您的应用程序中,该方法允许使用编码参数。

Private Shared Function MemoryStreamToString(ms As MemoryStream, enc As Encoding) As String
    Return Convert.ToBase64String(enc.GetString(ms.GetBuffer(), 0, CInt(ms.Length)))
End Function

Above function should be called like:

上面的函数应该像这样调用:

Dim streamText As String = MemoryStreamToString(response.GetResponseStream(), System.Encoding.ENCODINGTYPEHERE)

Go here for more information about Encoding MSDN

转到此处了解有关编码 MSDN 的更多信息

回答by ?s??? ????

In order to convert a stream to a string you need to use an encoding. Not sure if this is what you're looking for

为了将流转换为字符串,您需要使用编码。不确定这是否是您要找的

        Dim strReader As New StreamReader(dataStream, Encoding.UTF8)

        Dim yourString As String = strReader.ReadToEnd