草本枝稼

通过 HTTP POST 发送二进制数据
using System;
using System.Text;
using System.Net;
using System.Web;
using System.IO;

class Test
{
    public static void Main(){
        try{
            WebResponse response;
            HttpWebRequest request;
            request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/test.php");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            String filename = "test.jpg";
            // HTTP 参数名
            byte[] keyBytes = Encoding.UTF8.GetBytes(String.Format("filename={0}&data=", filename));

            FileStream fs = new FileStream(filename, FileMode.Open);
            byte[] buffer = new byte[8192];
            int n = fs.Read(buffer, 0, buffer.Length);
            byte[] dataArray = new byte[n];
            Array.Copy(buffer, dataArray, n);
            dataArray = HttpUtility.UrlEncodeToBytes(dataArray);

            request.ContentLength = keyBytes.Length + dataArray.Length;

            Stream dataStream = request.GetRequestStream();
            // 发送参数名
            dataStream.Write(keyBytes, 0, keyBytes.Length);
            // 发送名为 data 对应的值.
            dataStream.Write(dataArray, 0, dataArray.Length);
            dataStream.Close();

            response = (HttpWebResponse)request.GetResponse();
            // 读取服务器的返回, 在本应用中, 如果正常, 返回空字符串.
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            Console.Write(sr.ReadToEnd());

            response.Close();
        } catch (Exception e) {
            Console.Write("Error: " + e.ToString() + "\r\n");
        }
    }

}

posted on 2009-09-18 11:21  林声歌  阅读(2221)  评论(0编辑  收藏  举报