zoukankan      html  css  js  c++  java
  • 利用HttpWebRequest实现实体对象的上传

    一 简介     

         HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。另外,你可能预计需要显式地调用一个“Send”方法,实际上不需要。接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。

    二 场景

      就像上面所说的那样这两个对象的传输都是以流的方式在网络中传输的,如果我想要从客户端向服务器发送一个实体对象的数据该怎么解决呢?可能有的人说使用wcf等通信技术,但是对于我的应用场景来说有点小题大做,于是在网上找了点资料,实现了基于HttpWebReques的数据对象的传输。

    三 具体实现

     首先,创建需要传输的实体类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);
                }
            }
        }
    }

    注释写的很清楚,

    下面是服务端的代码:

    using System;
    using System.IO;
    using System.Text;
    using System.Web;
    using Newtonsoft.Json;
    
    namespace HttpWebClientTest
    {
        /// <summary>
        ///     UploadImagHandle 的摘要说明
        ///     create by peng.li 2015-5-30
        /// </summary>
        public class UploadImagHandle : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/xml";
                HandleMethod();
                //  context.Response.Write("Hello World");
            }
    
            public bool IsReusable
            {
                get { return false; }
            }
    
            private static void HandleMethod()
            {
                HttpContext httpContext = HttpContext.Current;
                Stream httpRStream = httpContext.Request.InputStream;
                var bytes = new byte[httpRStream.Length];
                httpRStream.Read(bytes, 0, bytes.Length); //读取请求流对象
                string req = Encoding.Default.GetString(bytes); //转换成字符串对象(这个字符串是json格式的)
                var postParameters = JsonConvert.DeserializeObject<PostParameters>(req); //(反序列化)
                int res = UploadImage(postParameters);
                httpContext.Response.Write(res);
            }
    
            public static int UploadImage(PostParameters postParameters)
            {
                string path = "E:/" + postParameters.Path;
                try
                {
                    if (!Directory.Exists(Path.GetDirectoryName(path)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                    }
                    File.WriteAllBytes(path, postParameters.FileByte);
                    return 1;
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }
    }

    这只是一个小的demo,希望能够起到抛砖引玉的作用,当然有表达错误的地方,也希望大家能指出来,一块学习,一块进步。

    本人的.NET学习技术交流群:226704167

    另附上demo下载链接:http://files.cnblogs.com/files/lip0121/HttpWebClientTestPostJson.rar

  • 相关阅读:
    一张图搞定OAuth2.0
    OAuth2.0的refresh token
    ACCESS_TOKEN与FRESH_TOKEN
    关于token和refresh token
    如何解决前后端token过期问题
    对外开放的接口验证方式
    python api接口认证脚本
    Python Thrift 简单示例
    整数中1出现的次数(从1到n整数中1出现的次数)
    连续子数组的最大和
  • 原文地址:https://www.cnblogs.com/lip0121/p/4539801.html
Copyright © 2011-2022 走看看