HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。另外,你可能预计需要显式地调用一个“Send”方法,实际上不需要。接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容
首先,创建需要传输的实体类PostParameters,这个实体类中有两个属性,一个是要传输的文件的文件流,另一个是文件路径(当然,因为我的需求是要上传图片的,没有做过多的扩展,后缀名,文件格式等的需求,可以根据自己的需求去做扩展)
public class PostParameters { // public string Name { get; set; } public Stream FStream { get; set; } public string Path { get; set; } }
下面是客户端的代码,利用HttpWebRequest传输实体对象数据
using System; using System.IO; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; namespace AshxRequestTest { internal class Program { private static void Main(string[] args) { PostJson("http://uploadimg.zhtx.com/UploadImagHandle.ashx", new PostParameters { Path = "hahah" }); } private static void PostJson(string uri, PostParameters postParameters) { string postData = JsonConvert.SerializeObject(postParameters); //将对象序列化 byte[] bytes = Encoding.UTF8.GetBytes(postData); //转化为数据流 var httpWebRequest = (HttpWebRequest) WebRequest.Create(uri); //创建HttpWebRequest对象 httpWebRequest.Method = "POST"; httpWebRequest.ContentLength = bytes.Length; httpWebRequest.ContentType = "text/xml"; using (Stream requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Count()); //输出流中写入数据 } var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse(); //创建响应对象 if (httpWebResponse.StatusCode != HttpStatusCode.OK) //判断响应状态码 { string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode); throw new ApplicationException(message); } } } }
摘抄至https://www.cnblogs.com/lip0121/p/4539801.html