利用HttpWebRequest模拟提交图片
利用HttpWebRequest模拟提交图片
最近在做排量post工具, 以前做的都是提交文字 这次需要post图片过去,弄了半天终于弄好了;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 |
/// <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" ;<br> //一些不需要的请求头 如果去掉不影响久尽量去掉 // req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; req.CookieContainer = cook; req.AllowAutoRedirect = true ; <br> //可能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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。