zoukankan      html  css  js  c++  java
  • 跨域提交时涉及中文编码的解决方案,同时解决post和get方案

        在做一个远程查询的实现时,涉及到了在客户服务器部署页面,通过post或者get方式提交请求,并获得查询结果。在实现时,由于服务端的默认编码为unicode编码,而客户端为gb2312的编码,结果导致中文不能被正常解析。在查阅相关资料后,通过如下的方案暂时得到解决,即需要用户提供目前提交编码方式,然后根据用户提供的编码方式进行编码转换来解析。因为目前没有找到直接识别传入编码格式的解决办法,只能需要用户自己在页面中来提交了。
        在用户通过远程提交时,如果是get方式,请求的参数通过Request.QueryString来提供,而如果是post方式时,则是通过Request.InputStream来提供,因此需要对他们进行分别的处理。
        下边的代码是我整理出来的一个可以通用的请求转换的方法,至于encode的获取,可以在页面代码中事先通过 Reques.Params["encode"]来获取,如:string encode = Request.Params["encode"]。
        这个方案目前仅适用于查询参数的解决,没有考虑涉及远程大数据量提交。

            /// <summary>
            /// 根据指定的编码格式返回请求的参数集合
            /// </summary>
            /// <param name="request">请求的字符串</param>
            /// <param name="encode">编码模式</param>
            /// <returns></returns>
            public static NameValueCollection GetRequestParameters(HttpRequest request,string encode)
            {
                NameValueCollection nv = null;
                Encoding destEncode = null;
                if (!String.IsNullOrEmpty(encode))
                {
                    try
                    {
                        destEncode = Encoding.GetEncoding(encode);
                    }
                    catch { }
                }

                if (request.HttpMethod == "POST")
                {
                    if (null != destEncode)
                    {
                        Stream resStream = request.InputStream;
                        byte[] filecontent = new byte[resStream.Length];
                        resStream.Read(filecontent, 0, filecontent.Length);
                        string postquery = Encoding.Default.GetString(filecontent);
                        nv = HttpUtility.ParseQueryString(postquery, Encoding.GetEncoding(encode));
                    }
                    else
                        nv = request.Form;
                }
                else
                {
                    if (null != destEncode)
                    {
                        nv = System.Web.HttpUtility.ParseQueryString(request.Url.Query, Encoding.GetEncoding(encode));
                    }
                    else
                    {
                        nv = request.QueryString;
                    }
                }
                return nv;
            }

  • 相关阅读:
    作业8: 软件工程学习总结
    用户体验——南通大学教务学生管理系统
    “构建之法互动游戏”感想
    第二次作业
    音乐播放器的发展演变
    C++用法的学习心得
    一、最后一次作业:软件工程学习总结
    设计一款给爸爸妈妈用的手机
    附加题1—— 我想搞懂的软工问题
    计算机病毒软件的发展演变
  • 原文地址:https://www.cnblogs.com/mincyw/p/mincyw.html
Copyright © 2011-2022 走看看