前端与HTTP通讯

//CommonMethod.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Xml;
using System.Security.Cryptography;

/// <summary>
///CommonMethod 的摘要说明
/// </summary>
public class CommonMethod
{
    public static Encoding EncodingType = Encoding.UTF8;

    #region 接口配置读取
    private static NameValueCollection config;

    private static object lockObj = new object();

    public static NameValueCollection InterFaceUrlConfigs
    {
        get
        {
            if (config == null)
            {
                lock (lockObj)
                {
                    if (config == null)
                    {
                        config = InitConfigs();
                    }
                }
            }
            return config;
        }
    }

    private static NameValueCollection InitConfigs()
    {
        NameValueCollection configs = new NameValueCollection();
        XmlDocument file = new XmlDocument();

        file.Load(System.Web.HttpContext.Current.Server.MapPath("InterFaceUrlConfig.xml"));

        XmlNodeList nodes = file.SelectNodes("root//interfaces//interface");

        foreach (XmlNode nd in nodes)
        {
            configs.Add(nd.Attributes["name"].Value, nd.Attributes["url"].Value);
        }
        return configs;
    }

    #endregion

    public CommonMethod()
    {
    }


    /// <summary>
    /// 设置http头
    /// 当需要鉴权401的时候使用
    /// </summary>
    /// <param name="wReq">WebRequest</param>
    /// <param name="username">用户登陆用户名</param>
    /// <param name="password">密码或验证码</param>
    public static void SetHttpRequestHeaderForDigest(WebRequest wReq, string username, string password)
    {
        if (HttpContext.Current.Session["WWW-Authenticate"] != null)
        {
            //注册时候走
            string str = HttpContext.Current.Session["WWW-Authenticate"].ToString();
            string Digestrealm = getvalue(str, "Digest realm");
            string qop = getvalue(str, "qop");
            string nonce = getvalue(str, "nonce");
            string opaque = getvalue(str, "opaque");

            string a1 = getMd5(username + ":" + Digestrealm + ":" + password);
            string a2 = getMd5("GET" + ":http://login.dbank.com/auth");

            DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳 
            long nc = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000;
            long cnonce = nc;
            string rs = getMd5(a1 + ':' + nonce + ':' + nc + ':' + cnonce + ':'
                    + qop + ':' + a2);

            StringBuilder sb = new StringBuilder("Digest ");
            sb.Append("username=\"").Append(username).Append("\",");
            sb.Append("realm=\"").Append(Digestrealm).Append("\",");
            sb.Append("nonce=\"").Append(nonce).Append("\",");
            sb.Append("uri=\"").Append("http://login.dbank.com/auth").Append("\",");
            sb.Append("cnonce=\"").Append(cnonce).Append("\",");
            sb.Append("nc=\"").Append(nc).Append("\",");
            sb.Append("response=\"").Append(rs).Append("\",");
            sb.Append("qop=\"").Append(qop).Append("\",");
            sb.Append("opaque=\"").Append(opaque).Append("\"");

            wReq.Headers.Add("Authorization", sb.ToString());
            HttpContext.Current.Session.Remove("WWW-Authenticate");
        }
        else
        {
            //登陆走
            NetworkCredential o = new NetworkCredential(username, password, "auth");
            CredentialCache myCache = new CredentialCache();
            myCache.Add(new Uri("http://login.dbank.com/auth"), "Digest", o);

            wReq.Credentials = o;
        }
    }

    public static string getMd5(string str)
    {
        byte[] result = EncodingType.GetBytes(str);    //tbPass为输入密码的文本框
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] output = md5.ComputeHash(result);
        string strMd5Pwd = BitConverter.ToString(output).Replace("-", "").ToLower();

        return strMd5Pwd;
    }

    private static string getvalue(string str, string keyname)
    {
        string r = "";
        string[] str1 = Regex.Split(Regex.Replace(str, "\"", ""), ",");
        foreach (string strs in str1)
        {
            if (strs.StartsWith(keyname))
            {
                r = Regex.Split(strs, "=")[1];
            }
        }
        return r;
    }


    #region GET方式
    /// <summary>
    /// 登陆
    /// </summary>
    /// <param name="wReq"></param>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public static string DoLogin(WebRequest wReq, string username, string password)
    {
        if (username != null && password != null)
        {
            SetHttpRequestHeaderForDigest(wReq, username, password);
            return DoRequest(wReq);
        }
        else
        {
            return "用户名或密码不能为空";
        }
    }


    /// <summary>
    /// 请求网络
    /// </summary>
    /// <param name="wReq"></param>
    /// <returns></returns>
    public static string DoRequest(WebRequest wReq)
    {
        //构造http响应的类
        try
        {
            WebResponse wResp = wReq.GetResponse();
            if (wResp.Headers["NSP_STATUS"] != null)
            {
                return wResp.Headers["NSP_STATUS"];
            }
            //实例化返回数据流
            Stream respStream = wResp.GetResponseStream();
            //将返回数据写到字符串里
            using (StreamReader reader = new StreamReader(respStream, EncodingType))
            {
                //返回内容
                return reader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
            {
                HttpContext.Current.Session["WWW-Authenticate"] = (ex.Response as HttpWebResponse).Headers["WWW-Authenticate"];
                return "401";
            }
            return (ex.Response as HttpWebResponse).StatusCode.ToString();
        }
    }

    #endregion

    #region POST
    /// <summary>
    /// 登陆
    /// </summary>
    /// <param name="wReq"></param>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <param name="urlParam">需要传的参数</param>
    /// <returns></returns>
    public static string DoLoginByPost(WebRequest wReq, string username, string password, string urlParam)
    {
        if (username != null && password != null)
        {


            SetHttpRequestHeaderForDigest(wReq, username, password);
            return DoRequestByPost(wReq, urlParam);
        }
        else
        {
            return "用户名或密码不能为空";
        }
    }

    /// <summary>
    /// 请求网络
    /// </summary>
    /// <param name="wReq"></param>
    /// <param name="postData">需要传的参数</param>
    /// <returns></returns>
    public static string DoRequestByPost(WebRequest wReq, string postData)
    {
        //构造http响应的类
        try
        {
            //设置请求的类型post
            wReq.Method = "post";
            //设置请求的参数体
            byte[] buffer = EncodingType.GetBytes(postData);
            wReq.ContentLength = buffer.Length;
            wReq.GetRequestStream().Write(buffer, 0, buffer.Length);
            WebResponse wResp = wReq.GetResponse();
            if (wResp.Headers["NSP_STATUS"] != null)
            {
                return wResp.Headers["NSP_STATUS"];
            }
            //实例化返回数据流
            Stream respStream = wResp.GetResponseStream();
            //将返回数据写到字符串里
            using (StreamReader reader = new StreamReader(respStream, EncodingType))
            {
                //返回内容
                return reader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
            {
                return "401";
            }
            return (ex.Response as HttpWebResponse).StatusCode.ToString();
        }
    }
    #endregion

    /// <summary>
    /// 解析requestData,
    /// key=value&key1=value1
    /// 返回key  value键值对
    /// </summary>
    /// <param name="requestData"></param>
    /// <returns></returns>
    public static NameValueCollection ParaRequestData(string dataInfo)
    {
        NameValueCollection nameValues = new NameValueCollection();
        Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
        MatchCollection mc = re.Matches(dataInfo);
        NameValueCollection nvc = new NameValueCollection();
        foreach (Match m in mc)
        {
            nameValues.Add(m.Result("$2"), m.Result("$3"));
        }
        return nameValues;
    }
}
 
 
//HttpHandler.ashx

<%@ WebHandler Language="C#" Class="HttpHandler" %>
using System;
using System.Web;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.SessionState;

/// <summary>
/// 启用session
/// </summary>
public class HttpHandler : IHttpHandler, IRequiresSessionState
{
    HttpSessionState currentSession;

    //static string str;
    /// <summary>
    /// 入口解析
    /// requestTpye:POST OR GET
    /// requestUrlPara:请求的url地址参数, 
    ///             客户端用js  encodeURIComponent进行编码,需要编码(encodeURIComponent(参数))
    ///             请求的url地址不在客户端显示,有服务端管理
    /// requestData:需要处理的数据
    ///             requestData:action=&username=&password=
    ///                 action:处理 获得client---getclient
    ///                              登录---login
    ///                              注册(获得验证码)---register1
    ///                              注册(第二步)---register2   (register2与login执行相同操作)
    ///                              其他再扩展
    ///                 username:用户名(登陆的邮箱,注册时的手机号)  不可为空,由客户端做验证
    ///                 password:用户密码(登陆的密码,注册时的验证码)  不可为空,由客户端做验证
    ///              
    ///                 
    /// </summary>
    /// <param name="context"></param>
    public void ProcessRequest(HttpContext context)
    {
        string requestTpye = string.Empty;
        string requestUrlPara = string.Empty;
        string requestData = string.Empty;
        currentSession = context.Session;
        try
        {
            string RetContent = string.Empty;
            
            //获取参数值
            if (context.Request.Params != null)
            {
                requestTpye = context.Request.Params["httptype"];
                requestUrlPara = HttpUtility.UrlDecode(context.Request.Params["requestUrlPara"]);
                requestData = context.Request.Params["httpdata"];
            }

            if ("uploadFile".Equals(requestData))
            {
                RetContent = ReceiveFiles(context);
            }
            else
            {
                //判断请求类型
                if (requestTpye == "get")
                {
                    RetContent = GetHttpInterface(requestUrlPara, requestData);
                }
                else if (requestTpye == "post")
                {
                    RetContent = PostHttpInterface(requestUrlPara, requestData);
                }
                else
                {
                    RetContent = "error";
                }
            }
            context.Response.Write(RetContent);
        }

        catch
        {

        }
    }

    /// <summary>
    /// http请求get方式
    /// </summary>
    /// <param name="urlPara">请求的http地址参数</param>
    /// <param name="requestData">数据部分</param>
    /// <returns>请求返回内容</returns>
    private string GetHttpInterface(string urlPara, string requestData)
    {
        try
        {
            string result = "";
            //构造http请求的类
            WebRequest wReq;
            //解析requestData
            NameValueCollection nameKeys = CommonMethod.ParaRequestData(requestData);
            switch (nameKeys["action"])
            {
                case "getclient":
                    wReq = WebRequest.Create(CommonMethod.InterFaceUrlConfigs["getclient"] + urlPara);
                    //获得client secret,只取一次值
                    if (currentSession["Client-Secret"] != null)
                    {
                        result = Convert.ToString(currentSession["Client-Secret"]);
                    }
                    else
                    {
                        result = CommonMethod.DoRequest(wReq);
                        currentSession["Client-Secret"] = result;
                    }
                    break;
                case "login":
                    wReq = WebRequest.Create(CommonMethod.InterFaceUrlConfigs["login"] + urlPara);
                    result = CommonMethod.DoLogin(wReq, nameKeys["username"], nameKeys["password"]);
                    break;
                case "register2":
                    wReq = WebRequest.Create(CommonMethod.InterFaceUrlConfigs["register1"] + urlPara);
                    result = CommonMethod.DoLogin(wReq, nameKeys["username"], nameKeys["password"]);
                    break;
                case "register1":
                    //str = CommonMethod.InterFaceUrlConfigs["register1"] + urlPara;
                    wReq = WebRequest.Create(CommonMethod.InterFaceUrlConfigs["register1"] + urlPara);
                    result = CommonMethod.DoRequest(wReq);
                    break;             
                case "logout":
                    wReq = WebRequest.Create(CommonMethod.InterFaceUrlConfigs["logout"] + urlPara);
                    result = CommonMethod.DoRequest(wReq);
                    currentSession.Remove("Client-Secret");
                    HttpContext.Current.Session.Remove("WWW-Authenticate");
                    break;
                default: break;
            }
            return result;
        }
        catch
        {
            //请求异常返回错误
            return "error";
        }
    }

    /// <summary>
    /// http请求post方式
    /// </summary>
    /// <param name="urlPara">请求的http地址参数</param>
    /// <param name="requestData">请求的参数体</param>
    /// <returns>请求返回内容</returns>
    private string PostHttpInterface(string urlPara, string requestData)
    {
        try
        {
            string result = "";
            //请求的参数体编码类型
            Encoding encoding = Encoding.Default;
            //构造http请求的类
            HttpWebRequest request;

            //解析requestData
            NameValueCollection nameKeys = CommonMethod.ParaRequestData(requestData);
            switch (nameKeys["action"])
            {
                case "getclient":
                    break;
                case "login":
                case "register2":
                    request = (HttpWebRequest)WebRequest.Create(CommonMethod.InterFaceUrlConfigs["login"]);
                    result = CommonMethod.DoLoginByPost(request, nameKeys["username"], nameKeys["password"], urlPara);
                    break;
                case "register1":
                    request = (HttpWebRequest)WebRequest.Create(CommonMethod.InterFaceUrlConfigs["register1"]);
                    result = CommonMethod.DoRequestByPost(request, urlPara);
                    break;
                case "up_init":
                    string url = HttpUtility.UrlDecode(nameKeys["url"]);
                    request = (HttpWebRequest)WebRequest.Create(url);
                    result = CommonMethod.DoRequestByPost(request, urlPara);
                    break;
                default: break;
            }
            return result;
        }
        catch
        {
            //请求异常返回错误
            return "error";
        }
    }

    /// <summary>
    /// 接收中转文件
    /// </summary>
    /// <param name="context"></param>
    private string ReceiveFiles(HttpContext context)
    {
        HttpPostedFile file = context.Request.Files["files"];
        //file.SaveAs(Path.Combine(context.Server.MapPath("."), HttpUtility.UrlDecode(file.FileName)));
        string result = UploadFileEx("http://upload.dbank.com/upload/up.php", context, file);
        return result;
    }
    
    /// <summary>
    /// 发送文件
    /// </summary>
    /// <param name="url"></param>
    /// <param name="context"></param>
    /// <param name="file"></param>
    /// <returns></returns>
    public string UploadFileEx( string url, HttpContext context, HttpPostedFile file)
    {
        string fileFormName = "files";
        string contenttype = file.ContentType;

        Uri uri = new Uri(url);

        string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
        //webrequest.CookieContainer = cookies;
        webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
        webrequest.Method = "POST";

        // 构造一个post请求的http头
        StringBuilder sb = new StringBuilder();
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"nsp_app\"\r\n\r\n");
        sb.Append(context.Request.Params["nsp_app"] + "\r\n");
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"nsp_fmt\"\r\n\r\n");
        sb.Append(context.Request.Params["nsp_fmt"] + "\r\n");
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"nsp_ts\"\r\n\r\n");
        sb.Append(context.Request.Params["nsp_ts"] + "\r\n");
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"nsp_key\"\r\n\r\n");
        sb.Append(context.Request.Params["nsp_key"] + "\r\n");
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"nsp_tstr\"\r\n\r\n");
        sb.Append(context.Request.Params["nsp_tstr"] + "\r\n");
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"");
        sb.Append(fileFormName);
        sb.Append("\"; filename=\"");
        sb.Append((file.FileName));
        sb.Append("\"");
        sb.Append("\r\n");
        sb.Append("Content-Type: ");
        sb.Append(contenttype);
        sb.Append("\r\n");
        sb.Append("\r\n");

        string postHeader = sb.ToString();
        byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

        // Build the trailing boundary string as a byte array
        // ensuring the boundary appears on a line by itself
        byte[] boundaryBytes =
        CommonMethod.EncodingType.GetBytes("\r\n--" + boundary + "\r\n");

        //FileStream fileStream = file.InputStream;
        long length = postHeaderBytes.Length + (long)file.ContentLength +
                                   boundaryBytes.Length;
        webrequest.ContentLength = length;

        Stream requestStream = webrequest.GetRequestStream();
        // 写入post头
        requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

        // 写入文件内容
        byte[] buffer = new Byte[file.ContentLength];
        file.InputStream.Seek(0, SeekOrigin.Current);
        file.InputStream.Read(buffer, 0, buffer.Length);

        requestStream.Write(buffer, 0, buffer.Length);

        // 写入post请求的尾
        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        //读取服务器的反馈消息
        StreamReader sr;
        try
        {
            WebResponse responce = webrequest.GetResponse();

            Stream s = responce.GetResponseStream();
           sr = new StreamReader(s);
        }
        catch (WebException ex)
        {
            //if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
            //{
            //    return "401";
            //}
            return (ex.Response as HttpWebResponse).StatusCode.ToString();
        }

        return sr.ReadToEnd();
    }
       
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
/* ----------- 注册 ----------- */
/**
*添加注册系统级别参数
*/
var buildDataForReg = function (data) {
    $.extend(data, {
        type: '1',
        nsp_app: 48257 //AppID
    });
    $.extend(data, {
        nsp_key: sign(data)//请求签名
    });
};

//获取参数
function getParamsForReg(params) {
    buildDataForReg(params);
    var urlP = "";
    $.each(params, function (k, v) {
        urlP += "&" + k + "=" + v;


    });
    return urlP.replace("&", "?");
}

function getRegister() {
    $("#timespan").val(new Date().getTime());
    var params =
    {
        mobile: $("#txtname").val(),
        client: $("#client").val(),
        nsp_ts: $("#timespan").val(),
        tpl: "b70bc7"
    };
    var urlParams = getParamsForReg(params);
    $.get("HttpHandler.ashx", { httptype: "get", requestUrlPara: encodeURIComponent(urlParams), httpdata: "action=register1" }, function (data) {
        if (data == "401") {
            //显示验证区域
            $("#step1").hide();
            $("#step2").show();
        }
        if (data == "1003") {
            alert("此账号已存在");
        }
    });
}























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值