开发者

Convert to Stream from a Url

I was trying to convert an Url to Stream 开发者_开发百科but I am not sure whether I am right or wrong.

protected Stream GetStream(String gazouUrl)
{
    Stream rtn = null;
    HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(gazouUrl);
    HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();

    using (StreamReader sReader = new StreamReader(aResponse.GetResponseStream(), System.Text.Encoding.Default))
    {
        rtn = sReader.BaseStream;
    }
    return rtn;
}

Am I on the right track?


I ended up doing a smaller version and using WebClient instead the old Http Request code:

private static Stream GetStreamFromUrl(string url)
{
    byte[] imageData = null;

    using (var wc = new System.Net.WebClient())
        imageData = wc.DownloadData(url);

    return new MemoryStream(imageData);
}


You don't need to create a StreamReader there. Just return aResponse.GetResponseStream();. The caller of that method will also need to call Dispose on the stream when it's done.


The current answer is missing an example in how to use GetResponseStream()

Here is an example

    // Creates an HttpWebRequest with the specified URL.
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    // Sends the HttpWebRequest and waits for the response.         
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    // Gets the stream associated with the response.
    Stream receiveStream = myHttpWebResponse.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    // Pipes the stream to a higher level stream reader with the required encoding format.
    StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
    Char[] read = new Char[256];
    // Reads 256 characters at a time.
    int count = readStream.Read( read, 0, 256 );
    Console.WriteLine("HTML...\r\n");
    while (count > 0)
        {
            // Dumps the 256 characters on a string and displays the string to the console.
            String str = new String(read, 0, count);
            Console.Write(str);
            count = readStream.Read(read, 0, 256);
        }
    Console.WriteLine("");
    // Releases the resources of the response.
    myHttpWebResponse.Close();
    // Releases the resources of the Stream.
    readStream.Close();

For more details see - https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.getresponsestream?view=net-5.0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜