这里接接口时未进行封装,记录时才临时做了一下,所以可能某些声明不太对。如果有问题自己看着微调下就好,不行就问。
(1)GET添加请求头Token
//根据接收的参数先创建个类 public class getSchoolData { public string OrganizeId { get; set; } } public string HttpGet (string url) { string result = string.Empty; HttpWebRequest reqS = (HttpWebRequest)WebRequest.Create(Url); reqS.Method = "GET"; //添加请求头 reqS.Headers.Add("Authorization", "Bearer " + accessToken); reqS.ContentType = "application/json; charset=utf-8"; HttpWebResponse resS = (HttpWebResponse)reqS.GetResponse(); Stream myResponseStream = resS.GetResponseStream(); StreamReader streamReader = new StreamReader(myResponseStream); result = streamReader.ReadToEnd(); streamReader.Close(); myResponseStream.Close(); //Response.Write(result.ToString()); 这里可以看看返回的数据啦~ // 解析返回的json数据(使用 jobject) JObject theResult = (JObject)JsonConvert.DeserializeObject(result); // 根据JSON结构自己修改{}里的key值 string finalResult = theResult["{Data}"].ToString(); // 此处需自己根据返回数据设置类去接收 json转实体 List<getSchoolData> listS = JsonConvert.DeserializeObject<List<getSchoolData>>(finalResult); // 得到返回的数据结果 foreach (getSchoolData s in listS) { Response.Write("这里的{s}就是每一条得到的数据啦") } }
(2).POST带参数 请求(传入字符串)
public string HttpPost(string url, string content) { string getAccessToken = ""; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; //#region 添加Post 参数 byte[] data = Encoding.UTF8.GetBytes(content); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } //#endregion HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { getAccessToken = reader.ReadToEnd(); reader.Close(); } JObject getToken = (JObject)JsonConvert.DeserializeObject(getAccessToken); // 同样根据接口规则去取得返回Token string getTheToken = getToken["{access_token}"].ToString(); // 后续操作参上GET }
A.aspx.cs内代码
{ Session["Access_Token"] = getTheToken; }
B.aspx.cs内代码
{ if (Session["Access_Token"] != null) { string token = Session["Access_Token"]; } }
for (int i = 0; i < Response.Cookies.Count; i++) { Response.Cookies[i].Expires = DateTime.Now.AddDays(-1); } Session.Clear(); Session.Abandon();