利用HttpWebRequest模拟提交图片

利用HttpWebRequest模拟提交图片

最近在做排量post工具, 以前做的都是提交文字 这次需要post图片过去,弄了半天终于弄好了;

 /// <summary>
    /// Post发送图片数据
    /// </summary>
    public Queusresult requestData(string uri, string imgUrl, List<dataModes> ListMode, Encoding en, CookieContainer cook)
    {
        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
        req.Method = "POST";
        req.ContentType = "application/octet-stream";
     //一些不需要的请求头 如果去掉不影响久尽量去掉 // req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; req.CookieContainer = cook; req.AllowAutoRedirect = true;
     //可能post了其他参数需要跟图片拼接,我这里没有 所以注释了 //StringBuilder postData = new StringBuilder(""); //foreach (dataModes m in ListMode) //{ // postData.AppendFormat("{0}={1}&", m.keys, m.values); //} //postData.AppendFormat("{0}={1}", "1", "1"); //Byte[] writData = ASCIIEncoding.ASCII.GetBytes(postData.ToString()); //读取图片 FileStream oStream = new FileStream(imgUrl, FileMode.Open, FileAccess.Read); BinaryReader oReader = new BinaryReader(oStream); Byte[] imgData = oReader.ReadBytes(Convert.ToInt32(oStream.Length)); //byte[] data3 = new byte[writData.Length + imgData.Length]; //System.Array.Copy(writData, 0, data3, 0, writData.Length); //System.Array.Copy(imgData, 0, data3, writData.Length, imgData.Length); req.ContentLength = imgData.Length; Stream stream = req.GetRequestStream(); stream.Write(imgData, 0, imgData.Length); stream.Close(); HttpWebResponse response = req.GetResponse() as HttpWebResponse; Stream str = response.GetResponseStream(); string html = ""; using (StreamReader strRead = new StreamReader(str, en)) { req.CookieContainer.Add(response.Cookies); html = strRead.ReadToEnd(); } Queusresult q = new Queusresult(); q.html = html; q.cookie = cook; return q;

 测试成功,如果有不懂的可以加加群交流 .Net技术交流区  86594082

posted @ 2014-01-26 10:15  伤心木乃伊  阅读(956)  评论(0编辑  收藏  举报