Thread: ASP.NET/C# Http Post Example

C# Http Post Example

public void WebRequestUploadSuccessTest()

        {

            // Setup user params

            string VideoFile = @"f:\vids\testvideo.avi";



            // Setup soap classes

            Authentication auth = new Authentication();

            auth.Url = "https://services.nirvanix.com/ws/Authentication.asmx";

            IMFS imfs = new IMFS();

            imfs.Url = "http://services.nirvanix.com/ws/IMFS.asmx";



            // Login and get sessionToken

            string sessionToken = auth.Login(appKey, Username, Password);

            // Get the upload node

            UploadNode node = imfs.GetUploadNode(sessionToken, new FileInfo(VideoFile).Length);

            // Format the URL with

            string url = "http://" + node.IPAddress + "/Upload.ashx?uploadToken=" + node.AccessToken + "&destFolderPath=/httpupload/";



            string response = UploadFilesToRemoteUrl(url, VideoFile);



            Console.Write(response);

        }



        /// <summary>

        /// A method to upload files to the remote server streaming.

        /// </summary>

        private string UploadFilesToRemoteUrl(string url, string file)

        {

            // Create a boundry

            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");



            // Create the web request

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            httpWebRequest.Method = "POST";

            httpWebRequest.KeepAlive = true;



            httpWebRequest.Credentials =

            System.Net.CredentialCache.DefaultCredentials;



            // Get the boundry in bytes

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");



            // Get the header for the file upload

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";



            // Add the filename to the header

            string header = string.Format(headerTemplate, "file", file);



            //convert the header to a byte array

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);



            // Add all of the content up.

            httpWebRequest.ContentLength = new FileInfo(file).Length + headerbytes.Length + (boundarybytes.Length * 2) + 2;



            // Get the output stream

            Stream requestStream = httpWebRequest.GetRequestStream();



            // Write out the starting boundry

            requestStream.Write(boundarybytes, 0, boundarybytes.Length);



            // Write the header including the filename.

            requestStream.Write(headerbytes, 0, headerbytes.Length);



            // Open up a filestream.

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);

            

            // Use 4096 for the buffer

            byte[] buffer = new byte[4096];



            int bytesRead = 0;

            // Loop through whole file uploading parts in a stream.

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)

            {

                requestStream.Write(buffer, 0, bytesRead);

                requestStream.Flush();

            }



            boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");



            // Write out the trailing boundry

            requestStream.Write(boundarybytes, 0, boundarybytes.Length);



            // Close the request and file stream

            requestStream.Close();

            fileStream.Close();



            WebResponse webResponse = httpWebRequest.GetResponse();



            Stream responseStream = webResponse.GetResponseStream();

            StreamReader responseReader = new StreamReader(responseStream);



            string responseString = responseReader.ReadToEnd();



            // Close response object.

            webResponse.Close();



            return responseString;

        }


developer.nirvanix.com/forums/p/56/126.aspx





Re: C# Http Post Example

technet.rapaport.com/Info/LotUpload/SampleCode/Full_Example.aspx


using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;

using System.Collections.Specialized;



namespace TechnetSamples

{


class Program

{
static void Main(string[] args)

{
string URLAuth = "https://technet.rapaport.com/HTTP/Authenticate.aspx";

WebClient webClient = new WebClient();



NameValueCollection formData = new NameValueCollection();

formData["Username"] = "myUser";

formData["Password"] = "myPassword";



byte[] responseBytes = webClient.UploadValues(URLAuth, "POST", formData);

string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);

webClient.Dispose();



string URL = "http://technet.rapaport.com/HTTP/Upload/Upload.aspx?Method=file";

string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);



webRequest.Method = "POST";

webRequest.ContentType = "multipart/form-data; boundary=" + boundary;



string FilePath = "C:\\test.csv";

formData.Clear();

formData["ticket"] = resultAuthTicket;

formData["ReplaceAll"] = "false";



Stream postDataStream = GetPostStream(FilePath, formData, boundary);



webRequest.ContentLength = postDataStream.Length;

Stream reqStream = webRequest.GetRequestStream();



postDataStream.Position = 0;



byte[] buffer = new byte[1024];

int bytesRead = 0;



while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)

{
reqStream.Write(buffer, 0, bytesRead);

}



postDataStream.Close();

reqStream.Close();



StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());

string Result = sr.ReadToEnd();

}



private static Stream GetPostStream(string filePath, NameValueCollection formData, string boundary)

{
Stream postDataStream = new System.IO.MemoryStream();



//adding form data

string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment .NewLine + "{1}";



foreach (string key in formData.Keys)

{
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate,
key, formData[key]));

postDataStream.Write(formItemBytes, 0, formItemBytes.Length);

}



//adding file data

FileInfo fileInfo = new FileInfo(filePath);



string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +

Environment.NewLine + "Content-Type: application/vnd.ms-excel" + Environment.NewLine + Environment.NewLine;



byte[] fileHeaderBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate,
"UploadCSVFile", fileInfo.FullName));



postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);



FileStream fileStream = fileInfo.OpenRead();



byte[] buffer = new byte[1024];



int bytesRead = 0;



while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)

{
postDataStream.Write(buffer, 0, bytesRead);

}



fileStream.Close();



byte[] endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--");

postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);



return postDataStream;

}

}

}