• 跨域调用接口——WebClient通过get和post请求api


    AJAX不可以实现跨域请求,经过特殊处理才行。一般后台可以通过WebClient实现跨域请求~

    //get 请求
            string url = string.Format("http://localhost:28450/api/values?str1=a&str2=b");
            WebClient wc = new WebClient();
            Encoding enc = Encoding.GetEncoding("UTF-8");
            Byte[] pageData = wc.DownloadData(url);DownloadString(url);
            string re = enc.GetString(pageData);

    //post 请求(注意Post请求都是传递Json过去)

            Person p=new Person(){Name="张三",Age=22};
            string postData = Convert.Serialize(p);
            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json");
            client.Headers.Add("ContentLength", postData.Length.ToString());
            Encoding enc = Encoding.GetEncoding("UTF-8");
            byte[] responseData = client.UploadData("http://localhost:28450/api/values", "POST", bytes);
            string re = enc.GetString(responseData);

    //调用接口Demo

    string url = "http://localhost:62691/SessionState/TransmitSession";//获取会话同步接口
               
                //调用接口进行同步
                string timeStamp = GetTimeStamp();//获取时间戳
                string sign = DESEncrypt.Encrypt(timeStamp, "dxqmp52c0esxymru");
                Person p=new Person(){Name="张三",Age=22,Gender=""};
                string postData =p;
                byte[] bytes = Encoding.UTF8.GetBytes(postData);
                WebClient client = new WebClient();
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("ContentLength", postData.Length.ToString());
                Encoding enc = Encoding.GetEncoding("UTF-8");
                byte[] responseData = client.UploadData(url, "POST", bytes);           
                string re = enc.GetString(responseData);
    View Code

    来源:http://blog.csdn.net/zhaoqi5705/article/details/14920667

  • 相关阅读:
    video 属性和事件用法大全
    微信小程序 组件通信相关知识整理
    JavaScript实现登录窗口的拖拽
    JS 各种宽高
    CSS3 Animation
    CSS3 Transition
    CSS3 Transform
    vue 回到页面顶部
    element-ui 动态换肤
    Chrome浏览器下自动填充的输入框背景
  • 原文地址:https://www.cnblogs.com/shuai7boy/p/6250671.html
Copyright © 2020-2023  润新知