JMK - 1 month ago 8
C# Question

Downloading a file via an HTTP Post, where am I going wrong?

I am trying to download a report from Datacash via an HTTP post using this page as a reference and I can't figure out where I am going wrong.

My method is below:

private static void DownloadDatacashData(int howManyDays)
{
string post, url, group, user, password, startDate, endDate, type, csvFile;

url = "https://reporting.datacash.com/reporting2/csvlist?";

group = "123456";
user = "autoreport";
endDate = DateTime.Now.ToString("yyyy-MM-dd");
type = "stl";

post = String.Format(@"group={0}&user={1}&password={2}&start_date={3}&end_date={4}&type={5}", group, user, password, startDate, endDate, type);

var request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
request.Method = "POST";
request.ContentLength = 0;

var postBytes = Encoding.ASCII.GetBytes(post);

request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
var requestStream = request.GetRequestStream();

requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();

var response = (HttpWebResponse)request.GetResponse();

var sr = new StreamReader(response.GetResponseStream());
sr.Close();

var sw = new StreamWriter("C:\\foo\\bar.csv", false);
sw.Write(csvFile);
sw.Flush();
sw.Close();
}


First of all, the post is performed. But I always get a file back with the text "Error: Report type not found". If I change the URL, I get an error so this URL is definitely responding to HTTP post. I have tried this with and without the ? in the initial URL, and with and without the ? at the start of the post string.

I have already tried to get in touch with Datacash's technical support and they couldn't help me. I sent them the code I am using and all I got back was that there wasn't anything wrong on their end.

The credentials are correct, the password is a combination of letters and numbers (no special characters).

I know that not many of you will have used datacash but looking at my code and the information here, is there anything obviously wrong with what I am doing? I am going around in circles.

Thankyou

Your code seems way too complicated for something like this. Try simplifying:

private static void DownloadDatacashData(int howManyDays)
{
var url = "https://reporting.datacash.com/reporting2/csvlist";
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "group", "123456" },
{ "user", "autoreport" },
{ "password", "foobar" },
{ "start_date", DateTime.Now.AddDays(howManyDays).ToString("yyyy-MM-dd") },
{ "end_date", DateTime.Now.ToString("yyyy-MM-dd") },
{ "type", "stl" },
};
byte[] result = client.UploadValues(url, values);
File.WriteAllBytes("C:\\foo\\bar.csv", result);
}
}