解决思路:
- 将获取的网络流转化成内存流
- 内存流位置指向0
- 内存流转化成字节流
//获取fileNamePath路径的网络流 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileNamePath); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); //将网络流写入内存流 MemoryStream memoryStream = new MemoryStream(); const int bufferLength = 1024; int actual; byte[] buffer = new byte[bufferLength]; while ((actual = stream.Read(buffer, 0, bufferLength)) > 0) { memoryStream.Write(buffer, 0, actual); } memoryStream.Position = 0; //将内存流转成字节流 byte[] bytes = new byte[memoryStream.Length]; memoryStream.Read(bytes,0,bytes.Length); memoryStream.Seek(0,SeekOrigin.Begin);
项目中进行代码的封装
/// <summary> /// 返回字节流 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="options"></param> /// <param name="param"></param> /// <param name="encoding"></param> /// <returns></returns> public static byte[] Post(string url, HttpOptions options, Dictionary<string, string> param, string encoding = "utf-8") { var req = CreateRequest(url, options); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; StringBuilder builder = new StringBuilder(); foreach (var key in param.Keys) { builder.Append(key).Append("=").Append(param[key]).Append("&"); } if (builder.Length > 0) { builder.Remove(builder.Length - 1, 1); } var arr = Encoding.GetEncoding(encoding).GetBytes(builder.ToString()); req.ContentLength = arr.Length; using (var stream = req.GetRequestStream()) { stream.Write(arr, 0, arr.Length); stream.Close(); using (var resp = GetResponse(req)) { var sr = resp.GetResponseStream(); MemoryStream memoryStream = StreamToMemoryStream(sr); return StreamToByte(memoryStream); } } } public static HttpWebRequest CreateRequest(string uri, HttpOptions options) { var req = (HttpWebRequest)WebRequest.Create(uri); req.Timeout = options.TimeOut; req.Proxy = null; req.KeepAlive = false; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87"; return req; } public static HttpWebResponse GetResponse(HttpWebRequest request) { var res = (HttpWebResponse)request.GetResponse(); return res; } /// <summary> /// 网络流转成内存流 /// </summary> /// <param name="sr"></param> /// <returns></returns> public static MemoryStream StreamToMemoryStream(Stream stream) { MemoryStream memoryStream = new MemoryStream(); const int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int actual; while ((actual = stream.Read(buffer,0,bufferLength)) > 0) { memoryStream.Write(buffer, 0, actual); } memoryStream.Position = 0; return memoryStream; } /// <summary> /// 内存流转成字节流 /// </summary> /// <param name="sr"></param> /// <returns></returns> public static byte[] StreamToByte(Stream sr) { byte[] bytes = new byte[sr.Length]; sr.Read(bytes, 0, bytes.Length); sr.Seek(0, SeekOrigin.Begin); return bytes; }
参考链接:https://blog.csdn.net/fengziyun/java/article/details/7414891