Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Here we will describe a simple procedure to make a request of type "multipart/form-data" from C# using the HttpWebRequest class. Taking as refence the article published in the web : Browsing_the_WEB_with_C_.asp .

Content

The big problem of this type of request is how to prepare the data package that will be passed to the class. For this, the more easy way to do this is making a string with the data in text form. You will must be careful with this, because if you put wrong a character or separator the package wont get to destiny successfully.

The next method make this action about a parameters collection, these parameters can be different type, because by this way you will can sending the file content.

"cs">private string GetPostData() 
{ 
    string boundary = "--" + this._Boundary; 
    int arrReqs = this._ParamsCollection.Count * 5; 
    string[] auxReqBody = new string[arrReqs]; 
    int count = 0; 
    foreach(ParamsStruct par in this._ParamsCollection) 
    { 
        auxReqBody[count] = boundary; 
        count++; 
        switch (par.Type) 
        { 
            case ParamsStruct.ParamType.File: 
            { 
                auxReqBody[count] = "Content-Disposition: file; name=\"" + par.Name + "\"; filename=\"" + par.GetOnlyFileName() + "\""; 
                count++; 
                auxReqBody[count] = "Content-Type: text/plain"; 
                count++; 
                auxReqBody[count] = ""; 
                count++; 
                auxReqBody[count] = par.StringValue; 
                count++; 
                break; 
            } 
            case ParamsStruct.ParamType.Parameter: 
            default: 
            { 
                auxReqBody[count] = "Content-Disposition: form-data; name=\"" + par.Name + "\""; 
                count++; 
                auxReqBody[count] = ""; 
                count++; 
                auxReqBody[count] = par.StringValue; 
                count++; 
                break; 
            } 
        } 
    } 
    auxReqBody[count] = boundary; 
    count++; 
    string requestBody = String.Join("\r\n",auxReqBody); 
    return requestBody;
} 

Then if we inform in the parameters collection : one parameter of type "Parameter", name "param1" and value "param1Value" and one parameter of type "File", name "file", file name "fileName1.txt" and value "Content of fileName1.txt", after run of this method you will obtain a text with this format:

--AaB03x\r\n
Content-Disposition: form-data; name="param1"\r\n
\r\n
param1Value\r\n
--AaB03x\r\n
Content-Disposition: file; name="file"; filename="fileName1.txt"\r\n
Content-Type: text/plain\r\n
\r\n
Content of fileName1.txt \r\n
--AaB03x\r\n

After this, we will use a method similar to this one, for sending the information to the required page.

"cs">public void PostData ()
{ 
    //Set URL 

    Uri urlUri = new Uri(_URL); 
    //Encoding postData 

    ASCIIEncoding encoding = new ASCIIEncoding(); 
    string postData = this.GetPostData(); 
    byte[] buffer = encoding.GetBytes( postData ); 
    // Prepare web request... 

    HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create(urlUri); 
    // We use POST ( we can also use GET ) 

    myRequest.Method = this._Method; 
    myRequest.AllowWriteStreamBuffering = true; 
    // Set the content type to a FORM 

    string auxContent = this._ContentType; 
    if (this._Boundary.Length > 0) 
        auxContent += "boundary=" + this._Boundary; 
    myRequest.ContentType = auxContent; 
    // Get length of content 

    myRequest.Accept = this._Accept; 
    myRequest.ContentLength = buffer.Length; 
    // Get request stream 

    Stream newStream = myRequest.GetRequestStream(); 
    // Send the data. 

    newStream.Write(buffer,0,buffer.Length); 
    // Close stream 

    newStream.Close(); 
    _myHttpWebResponse= (HttpWebResponse)myRequest.GetResponse(); 
    // Set the response to ResponseStream property 

    this._ResponseStream = _myHttpWebResponse.GetResponseStream();
} 

For finishing this, we must process the request stream returned by the required page. In this case I declare one property inside class that transform the response stream to string.

"cs">public string ResponseString
{ 
    get 
    { 
        string resultData = ""; 
        StreamReader streamRead = new StreamReader( _ResponseStream ); 
        Char[] readBuffer = new Char[256]; 
        // Read from buffer 

        int count = streamRead.Read( readBuffer, 0, 256 ); 
        while (count > 0) 
        { 
            // get string 

            resultData += new String( readBuffer, 0, count); 
            // Write the data 

            Console.WriteLine( resultData ); 
            // Read from buffer 

            count = streamRead.Read( readBuffer, 0, 256); 
        } 
        // Release the response object resources. 

        streamRead.Close(); 
        return resultData; 
    }
} 

In simple way, this will adapt to another content type. Remember that the key is the form for load the data package.

For SSL page type see request_SSL_from_C_.asp

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralDidn't Work :-(. Bad request exception (400)
edazccode
13:41 26 Nov '09  
I'm was trying to upload a text file but it threw an Exception of type 400 (Bad Request). I would appreciate if anyone can tell something wrong in my code.

I prepared the request this way:

//----------------------------------
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(sServiceUri));
req.Credentials = new System.Net.NetworkCredential("admin", "admin");
req.Method = "POST";
req.ContentType = "multipart/form-data;boundary=" + "AaB03x";
req.ContentLength = postBuffer.Length;
req.AllowWriteStreamBuffering = true;
req.Accept = "iso-8859-1";
//----------------------------------

And this is the data that I wrote to the request's stream (escape sequence chars are displayed):

Content-Disposition: file; name=\"filedata\"; filename=\"OneTextFile.text\"\r\nContent-Type: text/plain\r\n\r\nOn this text file I'm writing something\r\n--AaB03x
GeneralSending Multiple image
Member 4744029
17:09 1 Apr '09  
Hi All,

Greetings,

I am trying to send multiple jpeg's image but I have not had much luck. I have used the sample provided but it only allows you to send one image right?

Given the following multipart/form-data sample:

--AaB03x\r\n
Content-Disposition: form-data; name="param1"\r\n
\r\n
param1Value\r\n
--AaB03x\r\n
Content-Disposition: file; name="file"; filename="myimage.jpg"\r\n
Content-Type: image/jpeg\r\n
\r\n
\r\n
Content-Disposition: file; name="file"; filename="myimage2.jpg"\r\n
Content-Type: image/jpeg\r\n
\r\n
\r\n
--AaB03x\r\n--

When you use the following method PostData () how do you pass the the binary data for the two image in the following code:

newStream.Write(buffer,0,buffer.Length);

Does any have some sample code that allows you send multiple images using HttpWebRequest in C#.
How do you pass the raw binary data within the multipar/form-data???

Please help...

Kind regards

Jose
General{"The operation has timed out"}
Michael Sync
5:41 27 Aug '08  
Hello,

1) I'm using VS 2008 (no VS 2003 or 2005) and .NET 3.5 and I'm not able to the servicePointManager node in machine.config of C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG..

There is nothing inside .NET 1 folder..

2) I'm trying to post to https but I'm getting "timed out" error.. Any idea?

Thanks and Regards,
Michael Sync ( Blog: http://michaelsync.net)


Questionbinary data
p. tj
13:51 16 Apr '07  
this example is text files only. is there anyway to prepare the data package for image data(binary files).
AnswerRe: binary data
stibstibstib
1:26 7 Jun '07  
Hi,

Superb code examples and very straight forward to follow, i'm also wondering if this is possible with binary data?
GeneralRe: binary data
stibstibstib
4:01 7 Jun '07  
As a reply to my previous post, this is what i have so far (in vb.net), think i must be pretty close

first i build the top part of my string and encode to byte array

postData = Boundary & newline
postData += "Content-Disposition: form-data; name=""form""" & newline & newline
postData += "submit" & newline & Boundary & newline
postData += "Content-Disposition: form-data; name=""externalVideoRef""" & newline & newline
postData += cVidRef & newline & Boundary & newline
postData += "Content-Disposition: form-data; name=""videoTitle""" & newline & newline
postData += cVidTitle & newline & Boundary & newline
postData += "Content-Disposition: form-data; name=""videoFile""" & newline
postData += "Content-Type:" & fileVideo.PostedFile.ContentType & newline & newline

data = encoding.GetBytes(postData)


i then attach the file to be uploaded to this byte array


Dim Buffer(4096) As Byte, BlockSize As Integer
Dim TempStream As New MemoryStream
Do
BlockSize = myFileStream.Read(Buffer, 0, 4096)
If BlockSize > 0 Then TempStream.Write(Buffer, 0, BlockSize)
Loop While BlockSize > 0

data2 = TempStream.ToArray()


I then join the two byte arrays together and close the Http POST request byte array

postData = newline & Boundary & newline
data3 = encoding.GetBytes(postData)

'return the complete binary data
Dim newArray(data.Length + data2.Length + data3.Length) As Byte
data.CopyTo(newArray, 0)
data2.CopyTo(newArray, data.Length)
data3.CopyTo(newArray, data.Length + data2.Length)



This is then sent normally as httpwebrequest object


myWebReq = WebRequest.Create(formUrl)
myWebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; WindowsNT 5.1; SV1; .NET CLR 1.1.4322)"
myWebReq.Method = "POST"
myWebReq.ContentType = "multipart/form-data; boundary=" & Boundary
myWebReq.ContentLength = newArray.Length

Dim myStream As Stream = myWebReq.GetRequestStream()
myStream.Write(newArray, 0, newArray.Length)
myStream.Close()


its not quite there as the file doesnt get processed at the url location. am i missing something? any help would be gratefully appreciated!
QuestionRe: binary data(but how to code)
winart
18:18 22 Jul '07  
and i have no idea too about it.Frown

No pain no gain!

GeneralAny difference to post file to JSP page
vdonthi
9:26 6 Apr '07  
Hi I am using this code to post file to jsp page from c# client, when i post from c# client then the JSP page in server side is not able to recognize the file. Same JSP page can recognize the files from smple HTML page. is there any difference while post from c# httprequest object and simple HTML post?

Thanks,
DVSR
AnswerRe: Any difference to post file to JSP page
Pablo Russoniello
5:54 9 Apr '07  
Hi,

The JSP page was make for you or it is from another people?
If the first case try debugging the JSP page and view the content of the request, and compare both, the HTML post and the C# httprequest.
The content of both must be the same.

Tell me about this, please.
Generalopen the POST request in a browser
Zilberbal
20:40 4 Mar '07  
Hi,
The code you publish is great but what should i do inorder to show my request in the browser and not get the response my self.
is there a way for my to do that? in GET it is easy you just runa diffrent process with the url what abour POST?
Thanks,
Inbal
AnswerRe: open the POST request in a browser
Pablo Russoniello
2:40 5 Mar '07  
Hi,
If you want view the content of the GET in your browser you try paste the data into response object on the page class. D'Oh!

See you,
Polch.

GeneralRe: open the POST request in a browser
Zilberbal
1:17 8 Mar '07  
hi Polch,
I want POST not GET...
I would like to open a POST request in a browser.
Generalhow to read xml data from a http post
deepa l
13:16 22 Feb '07  
Hi all,

I am looking for some examples in C# to read and parse xml data that comes back in a http post. any help on this is greatly appreciated.



Thanks
Deepa.
AnswerRe: how to read xml data from a http post
Pablo Russoniello
2:53 23 Feb '07  
Hi Deepa,

To make a post to an url using httprequest from server side you can use the published example.
The data that comes back from post is returned by ResponseStream property. It is a stream data type then you convert the content of this property to another data type. For example, in this case the class have a property named ResponseString that convert the stream data type to string data type.

I hope that the information serves to you. Big Grin
Polch.
Generalread xml data from a http post
13:13 22 Feb '07  
Hi all,

I am looking for some examples in C# to read and parse xml data that comes back in a http post. any help on this is greatly appreciated.



Thanks
Deepa.
QuestionTried to use your class
alpha_krone
22:13 21 Feb '07  
Hi,
I tried to use your class.
I only changed one line of code which was to comment out
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy(); in PostData method.

To use it i tried the following
**Note HtpReq is your class.


htpReq htp = new htpReq(url);
ArrayList al = new ArrayList();
ParamsStruct param = new ParamsStruct("FILE", "Content of C:\\doco.xml", ParamsStruct.ParamType.File, "C:\\doco.xml");

al.Add(param);
htp.ParamsCollection = al;
htp.PostData();

This results in an internal server error.
ive tried the doco.xml over a browser multi-part post and it works fine.

Am i missing something?

Confused
AnswerRe: Tried to use your class
Pablo Russoniello
2:31 22 Feb '07  
Hi,

The line that you comment not affect to the execution of method, this is for HTTPS pages.

The problem is in ParamsStruct param = new ParamsStruct("FILE", "Content of C:\\doco.xml", ParamsStruct.ParamType.File, "C:\\doco.xml"); ,
when you declare a new file type paramstruct, the content of file must send like a Stream .
For example :
In my page I have an input tag of type file that I see from server side.
<INPUT id="file" type="file" name="file" style="WIDTH:600px" runat="server">

In my code on server side, when i instance the paramStruct class, I use the InputStream property of PostedFile, like this :
CustomWebRequest wr = new CustomWebRequest(url);
wr.ParamsCollection.Add(new ParamsStruct("file", file.PostedFile.InputStream, ParamsStruct.ParamType.File, file.PostedFile.FileName));

Other form for obtain this stream is using the methods on System.IO namespace.

Smile
GeneralRe: Tried to use your class
alpha_krone
16:04 22 Feb '07  
Wow thanks very much for your prompt reply =) apprecitae it. I will try as you suggested and let you know how i went.

Thanks


Last Updated 5 Mar 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010