HttpWebRequest向远程地址Post文件
/// <summary> /// 上传文件到远程服务器 /// </summary> /// <param name="url">远程服务器接收Api</param> /// <param name="postStream">文件流</param> /// <param name="contentType">内容类型默认application/octet-stream</param> /// <returns></returns> static public string PostFileByHttpWebRequest(string url, Stream postStream, string contentType = "application/octet-stream") { string result = string.Empty; HttpWebRequest request = null; try { ServicePointManager.DefaultConnectionLimit = int.MaxValue; request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 50000; request.Method = "POST"; request.ContentType = contentType; request.ContentLength = postStream.Length; using (Stream writer = request.GetRequestStream()) { WriteTo(postStream, writer, postStream.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { result = reader.ReadToEnd(); } } } catch (WebException ex) { request.Abort(); result = ex.Message.ToString(); } catch (Exception ex) { request.Abort(); result = ex.Message.ToString(); } finally { if (request != null) { request.Abort(); } } return result; } static private long WriteTo(Stream orignStream, Stream destStream, long totalSize) { int BufferSize = 4 * 1024; var buffer = new byte[BufferSize]; long alreadyRead = 0; while (alreadyRead < totalSize) { var readSize = orignStream.Read(buffer, 0, BufferSize); if (readSize <= 0) break; if (alreadyRead + readSize > totalSize) readSize = (int)(totalSize - alreadyRead); alreadyRead += readSize; destStream.Write(buffer, 0, readSize); } destStream.Flush(); return alreadyRead; }