Locked Error trying to send multipart form

  • lunes, 13 de agosto de 2012 18:02
     
      Tiene código
    Hi, I'm trying to send a multipart/form-data with the following code:

    HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create("http://the-server.com");
    request->Method = "POST";
    request->Host = "the-server";
    request->ContentType = "multipart/form-data; boundary=AaB03x";
    
    StreamWriter^ writer = gcnew StreamWriter(request->GetRequestStream());
    
    writer->WriteLine("--AaB03x");
    writer->WriteLine("Content-Disposition: form-data; name=\"first_field\"");
    writer->WriteLine();
    writer->WriteLine("the value");
    
    writer->WriteLine("--AaB03x");
    writer->WriteLine("Content-Disposition: form-data; name=\"second_field\"");
    writer->WriteLine();
    writer->WriteLine("the value");
    
    .
    .
    .
    
    writer->WriteLine("--AaB03x");
    writer->WriteLine("--");
    
    HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->GetResponse());
    

    But then the server returns an error; it says that the stream ended unexpectedly. I used Wireshark to look at the data sent and really not all the fields were sent. The transmission ended abruptly in the midway. I noticed ContentLength was set to some value, I don't know if it was correct.

    Do you have any idea what's happening? Do I have to set ContentLength manually?

Todas las respuestas

  • martes, 14 de agosto de 2012 1:49
     
     

    Solved! There was an error here:

    writer->WriteLine("--AaB03x");
    writer->WriteLine("--");

    Must be:

    writer->WriteLine("--AaB03x--");

    But anyway, that's not what I did. For some unknown reason, ContentLength was not being set properly, so that part of the data still wasn't getting sent. Since .Net is so quirky about this, I forgot this approach entirely and implemented my code using Sockets. Ugly but effective.

    .Net needs some improvement on HttpWebRequest/HttpWebResponse