使用HttpWebRequest进行文件传输

cookie根据具体情况使用,不需要可删除

返回值我固定给的空字符,自行修改

//登录
public string Login(string url, string body, ref CookieContainer cookie)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.CookieContainer = new CookieContainer();
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Method = "POST";
            //httpWebRequest.UserAgent = "";

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = UnicodeToString(streamReader.ReadToEnd());
            cookie.Add(httpWebResponse.Cookies);
            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();

            var jObject = JObject.Parse(responseContent);
            return "";
        }





//get
        public static string GetHttp(string url, CookieContainer cookie)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Method = "GET";
            httpWebRequest.CookieContainer = cookie;
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = UnicodeToString(streamReader.ReadToEnd());
            httpWebResponse.Close();
            streamReader.Close();
            return responseContent;

        }




/// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file">图片的物理路径</param>
        /// <param name="cookie"></param>
        public string PostPhoto(string url, string file, CookieContainer cookie)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            wr.CookieContainer = cookie;
            Stream rs = wr.GetRequestStream();
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, "photo", file, "image/jpeg");
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                string body = UnicodeToString(reader2.ReadToEnd());
                var jObject = JObject.Parse(body);
                return "";
            }
            catch (Exception)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
            return "";
        }









/// <summary>
        /// post含文件参数 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public string  PostFile(string url, string body, CookieContainer cookie)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            wr.CookieContainer = cookie;
            Stream rs = wr.GetRequestStream();
            string[] arrs = body.Split('&');
            foreach (var item in arrs)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string[] arr = item.Split('=');
                string header = "";
                if (arr[0] == "file")
                {
                    //文件

                    //string file = System.Web.HttpContext.Current.Server.MapPath(arr[1]);
                    header = "Content-Disposition: form-data; name=\"" + arr[0] + "\"; filename=\"" + arr[1] + "\"\r\nContent-Type: image/jpeg\r\n\r\n";
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    rs.Write(headerbytes, 0, headerbytes.Length);
                    FileStream fileStream = new FileStream(arr[1], FileMode.Open, FileAccess.Read);
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        rs.Write(buffer, 0, bytesRead);
                    }
                    fileStream.Close();

                }
                else
                {
                    //非文件
                    header = "Content-Disposition: form-data; name=\"" + arr[0] + "\"\r\n\r\n" + arr[1] + "\r\n";
                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                    rs.Write(headerbytes, 0, headerbytes.Length);
                }
            }

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                string result = UnicodeToString(reader2.ReadToEnd());
                //var jObject = JObject.Parse(result);
                return "";
            }
            catch (Exception)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
            return "";
        }



 

调用实例

//其他请求需要cookie验证身份的情况
CookieContainer cookie = new CookieContainer();

//登录,获取cookie
WebApi.Login("url", "username=123&password=123", ref cookie)

//post传输文件
WebApi.PostPhoto("url", "文件物理路径", cookie);

//post传多个参数(含文件)
WebApi.PostFile("url", "file=文件物理路径&key1=value1&key2=value2", cookie);

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值