rusty rusty - 1 year ago 56
C# Question

Saving a HTTP get response to a file

I can not get the HTTP response to be saved to a text file. I can make a get request and I can see that it goes through and I get the response I want but it doesn't save to a file. My code is below, I have commented out the other solution I have tried.

protected void Button1_Click(object sender, EventArgs e)
string input = TextBox1.Text;
string sURL;
sURL = "" + input + "/";
HttpWebRequest wrGETURL = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse wrResponse = (HttpWebResponse)wrGETURL.GetResponse();
StreamWriter SW = new StreamWriter(@"C:\Users\user\Desktop\API_Call_Test.txt");
Stream DataStream = wrResponse.GetResponseStream();
StreamReader SR = new StreamReader(DataStream);
string AllResponse = SR.ReadToEnd();
//var file = File.Open(@"C:\Users\user\Desktop\API_Call_Test.txt", FileMode.Create);


The Wireshark analysis of the TCP stream:

GET /api1000/key/host/ HTTP/1.1
Connection: Keep-Alive

HTTP/1.1 200 OK
Server: nginx
Date: Fri, 12 Aug 2016 16:31:15 GMT
Content-Type: text/xml
Content-Length: 909
Age: 0

<?xml version="1.0" encoding="UTF-8"?>
<asname>CloudFlare, Inc.</asname>
<country_name>United States</country_name>
<city_name>San Francisco</city_name>
<continent_name>North America</continent_name>

Answer Source

Well, that would be something like below. I think you can adapt it just fine.

string url = "";
string file = "response.txt";
string content = string.Empty;

// set up request/response
var request = (HttpWebRequest) WebRequest.Create(url);
var response = (HttpWebResponse) request.GetResponse();
var stream = response.GetResponseStream();

// read response content
using (var reader = new StreamReader(stream ?? new MemoryStream(), Encoding.UTF8))
    content = reader.ReadToEnd();

// write to file on desktop
    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), file),