M
M
martensit2020-06-23 15:02:44
C++ / C#
martensit, 2020-06-23 15:02:44

C# (HttpWebRequest) Get POST response as byte[]?

string postData = "post string";
        byte[] data = Encoding.ASCII.GetBytes(postData);
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://122.233.155.155:80");
        req.Method = "POST";
        req.ContentLength = postData.Length;
        req.Timeout = 10000;
        using (Stream stream = req.GetRequestStream()) stream.Write(data, 0, data.Length);
        using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
        {
            string s = reader.ReadToEnd();
            Console.WriteLine(s);
        }

So I get the answer in the form of a string, but how to get it in the form of an array of bytes byte[] ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LiptonOlolo, 2020-06-23
@martensit

using System.Net;

string postData = "post string";
byte[] data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://122.233.155.155:80");
req.Method = "POST";
req.ContentLength = postData.Length;
req.Timeout = 10000;
using (Stream stream = req.GetRequestStream()) stream.Write(data, 0, data.Length);
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
    var buffer = new byte[response.ContentLength];
    response.GetResponseStream().Read(buffer, 0, buffer.Length);
    Console.WriteLine(buffer.Length);
}

P
Peter, 2020-06-23
@petermzg

So response.GetResponseStream() returns the Stream you want.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question