1. 程式人生 > >C#跨域 (後臺請求)

C#跨域 (後臺請求)

A 下載引用

引用---管理NuGet程式包--下載ServiceStack.Text安裝、引用ServiceStack.Text.dll

B 用流跨域調json包,會出現轉義字元,可使用 JsonSerializer.DeserializeFromString來解析json

呼叫程式碼(get)

注意DXRes中設的值要與json中的key值一致

  private static string GetStr(string str, string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);

            string rtn = reader.ReadToEnd();

            DXRes res = JsonSerializer.DeserializeFromString<DXRes
>(rtn); string ASS = res.A; string BSS = res.B; return ASS;}
呼叫程式碼(post)

注意 LoginRes中設post需要代入的值

 public static string ClosePositionTest()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            LoginReq req = new LoginReq();
            req.Guid = Guid.NewGuid().ToString();
            req.LoginId = string.Format("xxx");
            byte[] bytes = Encoding.UTF8.GetBytes(JsonSerializer.SerializeToString(req));

            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Flush();
            requestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string rtn = reader.ReadToEnd();
            return rtn
}

解析json(get為例)
   HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);

            string rtn = reader.ReadToEnd();

            Dx Res res = JsonSerializer.DeserializeFromString<DxRes>(rtn);
            string pc = res.PCOnlineCount;
            string mobile = res.MobileCount;
            return pc;