c#实现ajax通信:向后台发送JSON字符串,接收响应字符串,并转换为对象

2017-10-07 19:44:49来源:CSDN作者:luanpeng825485697人点击

分享

全栈工程师开发手册 (作者:栾鹏)

c#教程全解

c#实现ajax通信,通过向服务器后台发送json数据,接收响应数据提交给前台。

其中包含两个主要函数,发送数据,接收响应数据的Http请求响应函数。另一个是将对象转化为JSON字符串的序列化函数。

需要下载并在引用空间中引入Newtonsoft.Json.dll,下载

using Newtonsoft.Json.Linq;using Newtonsoft;using Newtonsoft.Json;/// <summary>/// 向服务器后台发送json数据,需要引入Newtonsoft.Json.dll/// </summary>/// <param>请求地址</param>/// <param>json键值对</param>/// <returns></returns>public static JObject ajax(string urlpath, Dictionary<String, String> diclist){    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlpath);    req.Method = "POST";    req.ContentType = "application/x-www-form-urlencoded";    //设置参数,并进行URL编码    //虽然我们需要传递给服务器端的实际参数是JsonParas(格式:[{"UserID":"0206001","username","ceshi"}])    //但是需要将字符串参数构造成键值对的形式,注:"paramaters=["userid":"206001","username","ceshi"}]"    //其中键paramaters为webservice接口函数的参数名,值为经过序列化的Json数据字符串    //最后将字符串参数进行url编码    String poststr = buildQueryStr(diclist);    byte[] payload = Encoding.UTF8.GetBytes(poststr);    req.ContentLength = payload.Length;    //发送请求,获得请求流    Stream writer;    try    {        writer = req.GetRequestStream();   //获取用于写入请求数据的Stream对象    }    catch (Exception)    {        writer = null;        MessageBox.Show("连接服务器失败");        return null;    }    //将请求参数写入流    writer.Write(payload, 0, payload.Length);    writer.Close();  //关闭请求流    string strvalue = "";   //srevalue为http响应所返回的字符流    HttpWebResponse response;    try    {        //获得响应流        response = (HttpWebResponse)req.GetResponse();    }    catch (WebException ex)    {        response = ex.Response as HttpWebResponse;    }    Stream s = response.GetResponseStream();    StreamReader reader = new StreamReader(s);    strvalue = reader.ReadToEnd();    reader.Close();    s.Close();    JObject JSONobj = JObject.Parse(strvalue);    //lei.ziji = JsonConvert.DeserializeObject<user_me_back>(JSONobj["data".ToString()]);  //将字符串转化为类实例    return JSONobj;}//将键值对序列转化为请求网址字符串public static String buildQueryStr(Dictionary<String,String> diclist){    Dictionary<string, string> dd = new Dictionary<string, string>();    dd.Add("key1", "value1");    string aa = dd["key1"];    string poststr = "";    foreach (var item in diclist)    {        poststr += item.Key + "=" + HttpUtility.UrlEncode(item.Value,Encoding.UTF8)+"&";    }    poststr = poststr.Substring(0, poststr.LastIndexOf("&"));    return poststr;}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台