REST接口POST方法发送文件到服务器(C#)

using System;
using System.IO;
using System.Net;
using System.Text;

namespace xxxx
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http###files/Cygwin.pdf");
            FileStream fs = new FileStream(@"D:\Cygwin.ISO", FileMode.Open, FileAccess.Read);
            Byte[] bytes = new Byte[10240];
            request.Method = "POST";
            request.Proxy = null;
            request.Headers.Add("XXX", "XXX");
            request.ContentType = "application/octet-stream";
            Stream dataStream = request.GetRequestStream();
            int count = fs.Read(bytes, 0, 10240);
            while (count != 0)
            {
                dataStream.Write(bytes, 0, count);
                count = fs.Read(bytes, 0, 10240);
            }
            fs.Close();
            dataStream.Close();
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Close();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("!!!!!!ERROR!!!!!!!!" + ex.ToString() + "!!!!!!!!ERROR!!!!!!!!");
            }




        }
    }
}


代码可能有误

posted @ 2012-08-03 14:52  gitran  阅读(383)  评论(0编辑  收藏  举报