Simulating HTTP Post  
Author Message
TELOPHASE





PostPosted: .NET Framework Networking and Communication, Simulating HTTP Post Top

Hello all, i have made an HTML document which allows me to upload a file to a website without actually visting it.

I am using C# and i wanted the way i could do the uploading part programatically so that there is no user intervention.

I tried using HttpWebRequest and HttpWebResponse classes but in vain.

Any method to simulate the file upload is appreciated.

Inshort i want the replicate the action of the HTML file below, programatically using C#

Thanks for taking your time off and reading this post.

Have a nice day/night :)

----------------------------------------------------------------------------------------

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>RapidShare Webhosting + Webspace</title><link rel="stylesheet" href=" http://www.hide-link.com/ ; type="text/css"></head>
<body style="background-color:transparent">
<form action=" http://www.hide-link.com/ ; method="post" enctype="multipart/form-data" target="_blank" >
<input size="20" name="filecontent" type="file" style="font-family:monospace"><br />
<input name="u" value="Upload!" type="submit">
</form>
</body>
</html>

----------------------------------------------------------------------------------------


.NET Development15  
 
 
PJ. van de Sande





PostPosted: .NET Framework Networking and Communication, Simulating HTTP Post Top

Here is a class from my own framework, this handles post file uploads. You only have to change if you need more values like username and password:

If have uploaded the full code files here, bankbuddyonline.nl


using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace Max.Net
{
    [ComVisible( true )]
    [InterfaceType( ComInterfaceType.InterfaceIsDual )]
    [Guid( "035AE423-5EC4-4d26-B256-49F8E274BD1C" )]
    public interface _HttpPostFileUpload
    {
        event FileUploadEventHandler UploadStarted;
        event FileUploadEventHandler UploadInProgress;
        event FileUploadEventHandler UploadFinished;
        event FileUploadExceptionEventHandler UploadException;
        event EventHandler UploadCanceled;

        /// <summary>
        /// Gets the URL that will be used to send the data to.
        /// </summary>
        string URL
        {
            get;
            set;
        }

        /// <summary>
        /// Gets a indiction whether a upload process is running.
        /// </summary>
        bool Uploading
        {
            get;
        }

        /// <summary>
        /// Starts uploading a file.
        /// </summary>
        /// <param name="filepath">The filepath.</param>
        void Upload( string filepath );

        /// <summary>
        /// Cancel the upload process.
        /// </summary>
        void Cancel();
    }

    [ComVisible( true )]
    [ComSourceInterfaces( typeof ( IFileUploadEvents ) )]
    [ClassInterface( ClassInterfaceType.None )]
    [Guid( "4AD6F2C3-7EB4-4ead-B2BC-A47848F314E9" )]
    public class HttpPostFileUpload : FileUpload, _HttpPostFileUpload
    {
        private string _url;

        /// <summary>
        /// Gets the URL that will be used to send the data to.
        /// </summary>
        public string URL
        {
            get
            {
                return _url;
            }
            set
            {
                _url = value;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="HttpPostFileUpload"/> class.
        /// </summary>
        [Obsolete("Don't use this method within .NET, this is for COM only!", true)]
        public HttpPostFileUpload() : base()
        {
            // Use for COM+ Interop only!
        }

        /// <summary>
        /// Instantiate a new instance of <see cref="HttpPostFileUpload"/>.
        /// </summary>
        /// <param name="url">The URL that will be used to send the data to.</param>
        public HttpPostFileUpload( string url ) : base()
        {
            // Check arguments.
            if ( url == null )
            {
                throw new ArgumentNullException( url );
            }

            _url = url;
        }

        /// <summary>
        /// Upload in a blocking way.
        /// </summary>
        /// <param name="filepath">The filepath.</param>
        protected override void DoUpload( string filepath )
        {
            // Create a FileInfo object of the file.
            FileInfo fileInfo = new FileInfo( filepath );

            // Instantiate a new WebRequest.
            string boundary = "----------" + DateTime.Now.Ticks.ToString( "x" );
            HttpWebRequest webrequest = (HttpWebRequest) WebRequest.Create( URL );
            webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webrequest.Method = "POST";
            webrequest.Timeout = 5000;
            webrequest.Proxy = WebProxy.GetDefaultProxy();
            webrequest.Credentials = CredentialCache.DefaultCredentials;

            // Create the post message header.
            byte[] postHeaderBytes = CreateHeaderFile( boundary, "userfile", filepath );

            // Build the trailing boundary string as a byte array
            // ensuring the boundary appears on a line by itself
            byte[] boundaryBytes = Encoding.ASCII.GetBytes( "\r\n--" + boundary + "\r\n" );

            // Create the Stream objects.
            FileStream fileStream = null;
            Stream requestStream = null;

            try
            {
                // Lookup if the upload is canceled.
                if ( Canceled )
                {
                    OnUploadCanceled();
                    return;
                }

                // Instantiate the local FileStream.
                fileStream = new FileStream( filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
                long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                webrequest.ContentLength = length;

                // Get the request stream from the webrequest.
                requestStream = webrequest.GetRequestStream();

                // Rise UploadStarted event.
                OnUploadStarted( new FileUploadEventArgs( fileInfo.Name, (int) fileInfo.Length, 0 ) );

                // Write out our post header
                requestStream.Write( postHeaderBytes, 0, postHeaderBytes.Length );

                // Write out the file contents
                byte[] buffer = new Byte[checked( (uint) Math.Min( 4096, (int) fileStream.Length ) )];
                int bytesRead = 0;
                long totalBytes = 0;

                // Read the bytes from the local file stream.
                while ( ( bytesRead = fileStream.Read( buffer, 0, buffer.Length ) ) != 0 )
                {
                    // Lookup if the upload is canceled.
                    if ( Canceled )
                    {
                        OnUploadCanceled();
                        return;
                    }

                    // Write the readed bytes to the request stream.
                    requestStream.Write( buffer, 0, bytesRead );
                    totalBytes += bytesRead;

                    // Raise UploadInProgress event.
                    OnUploadInProgress( new FileUploadEventArgs( fileInfo.Name, (int) fileInfo.Length, (int) totalBytes ) );
                }

                // Write out the trailing boundary
                requestStream.Write( boundaryBytes, 0, boundaryBytes.Length );

                // Get response.
                using ( WebResponse response = webrequest.GetResponse() )
                {
                    Stream responseStream = null;

                    try
                    {
                        // Get response stream.
                        responseStream = response.GetResponseStream();
                    }
                    finally
                    {
                        // Close response stream when it exists.
                        if ( responseStream != null )
                        {
                            responseStream.Close();
                        }

                        // Close the response.
                        response.Close();
                    }
                }
            }
            finally
            {
                // Cleanup uses.
                if ( requestStream != null )
                {
                    try
                    {
                        requestStream.Close();
                    }
                    catch
                    {
                        // Eat up exception.
                    }
                }

                if ( fileStream != null )
                {
                    try
                    {
                        fileStream.Close();
                    }
                    catch
                    {
                        // Eat up exception.
                    }
                }

                if ( webrequest != null )
                {
                    try
                    {
                        // Abort webrequest.
                        webrequest.Abort();
                    }
                    catch ( WebException caught )
                    {
                        // Eat up exception and close
                        // response then exists.
                        if ( caught.Response != null )
                        {
                            caught.Response.Close();
                        }
                    }
                }
            }

            // Lookup if the upload is canceled.
            if ( Canceled )
            {
                // Raise UploadCanceled event.
                OnUploadCanceled();
            }
            else
            {
                // Raise UploadFinished event.
                OnUploadFinished( new FileUploadEventArgs( fileInfo.Name, (int) fileInfo.Length, (int) fileInfo.Length ) );
            }
        }

        protected virtual byte[] CreateHeaderFile( string boundary, string fileFormName, string filePath )
        {
            // Build up the post message header.
            StringBuilder sb = new StringBuilder();
            sb.Append( "--" );
            sb.Append( boundary );
            sb.Append( "\r\n" );
            sb.Append( "Content-Disposition: form-data; name=\"" );
            sb.Append( fileFormName );
            sb.Append( "\"; filename=\"" );
            sb.Append( Path.GetFileName( filePath ) );
            sb.Append( "\"" );
            sb.Append( "\r\n" );
            sb.Append( "Content-Type: " );
            sb.Append( "application/octet-stream" );
            sb.Append( "\r\n" );
            sb.Append( "\r\n" );

            // Return te post message header in a byte array encoded as UTF8.
            return Encoding.UTF8.GetBytes( sb.ToString() );
        }
    }
}

 



 
 
Augustin Calin





PostPosted: .NET Framework Networking and Communication, Simulating HTTP Post Top

Hello, TELOPHASE!

I'm not sure if you found the answer, here is how I do it:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);

req.Method = "POST";

req.ContentLength = (long)postData.Length;

using(Stream s = req.GetRequestStream()) {

s.Write(postData.ToArray(), 0, (int)postData.Length);

postData.Close();

}

WebResponse resp = req.GetResponse();

resp.Close();

where: - uploadUrl is the address of an HTML page (see bellow) and postData is an MemoryStream containing data to be uploaded.

On server I have an aspx page with form enctype="multipart/form-data". On Page_Load...

byte[] theData = null;

if(Request.ServerVariables["REQUEST_METHOD"].ToString().ToUpper() == "POST") {

theData = Request.BinaryRead(Request.ContentLength);

string picName = "now.jpg";

FileStream stm = new FileStream(Server.MapPath("images/" + picName), System.IO.FileMode.Create);

stm.Write(theData, 0, (int)theData.Length);

stm.Close();

}

I used this for uploading pictures using an application deployed in a smartphone.



 
 
Ntc





PostPosted: .NET Framework Networking and Communication, Simulating HTTP Post Top

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);

req.Method = "POST";

req.ContentLength = (long)postData.Length;

using(Stream s = req.GetRequestStream()) {

s.Write(postData.ToArray(), 0, (int)postData.Length);

postData.Close();

}

WebResponse resp = req.GetResponse();

resp.Close();

Augustin, the var postData it's stream type

can you give a complete example I'm newer on this and I'm trying to develop a smartphone aplication where I upload and download files where the name are dynamic.

Thanks


 
 
lchase4411





PostPosted: .NET Framework Networking and Communication, Simulating HTTP Post Top

I'm trying to do something similar but I keep seeing the same examples and code snippets. Does anyone know how I can navigate to a url with POST variables rather than posting and reading the response or just posting without caring about the response

Basically, I have an external slave web-site that has an integration page for authentication and I just need to open a window navigating to the url with POST variables of usrename/token so that it can authenticate however it wants to and then redirect to it's internal default page.

So, navigate+post and look away, done.