I've got a winforms application I'm writing that posts files to a web application (not mine). I've got things working just fine as far as posting the files themselves go, my issue is that I'd like to provide some indication of how far along I am with the sending the request.
The code below is my attempt to use BeginGetResponse to that end - and this is where I discovered that the Request still blocks.
Any suggestions on where I can begin to look?
public void Dummy()
{
Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("key", "something");
HttpWebRequest hr = WebRequest.Create("http://somesite.com/api/something.xml") as HttpWebRequest;
string bound = "----------------------------" + DateTime.Now.Ticks.ToString("x");
hr.ContentType = "multipart/form-data; boundary=" + bound;
hr.Method = "POST";
hr.KeepAlive = true;
hr.Credentials = CredentialCache.DefaultCredentials;
byte[] boundBytes = Encoding.ASCII.GetBytes("\r\n--" + bound + "\r\n");
string formDataTemplate = "\r\n--" + bound + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
Stream s = hr.GetRequestStream();
foreach (string key in fields.Keys)
{
byte[] formItemBytes = Encoding.UTF8.GetBytes(
string.Format(formDataTemplate, key, fields[key]));
s.Write(formItemBytes, 0, formItemBytes.Length);
}
s.Write(boundBytes, 0, boundBytes.Length);
string headerTemplate =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
List<string> files = new List<string> { Server.MapPath("/Images/Phillip.jpg") };
foreach (string f in files)
{
byte[] headerBytes = Encoding.UTF8.GetBytes(
String.Format(headerTemplate, "image", f));
s.Write(headerBytes, 0, headerBytes.Length);
FileStream fs = new FileStream(f, FileMode.Open, FileAccess.Read);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, buffer.Length);
}
s.Write(boundBytes, 0, boundBytes.Length);
fs.Close();
}
s.Close();
string respString ="";
hr.BeginGetResponse((IAsyncResult res) =>
{
WebResponse resp = ((HttpWebRequest)res.AsyncState).EndGetResponse(res);
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respString = respReader.ReadToEnd();
resp.Close();
resp = null;
}, hr);
while (!hr.HaveResponse)
{
Debug.Write("hiya bob!");
Thread.Sleep(150);
}
Debug.Write(respString);
hr = null;
}