已經獲得code現在要訪問
“https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code”
返回的JSON數據包如下:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
現在要獲取openid,怎麼在後台訪問這個鏈接回調後處理json數據,然後篩選出openid,直接賦給變量。
最終目的:string openid=回調後處理篩選好的openid。
HttpWebRequest請求那個地址獲取返回的json數據然後前後截取或者建立json對應的類,用Newtonsoft.Json.Net20.dll序列化為你的類就可以訪問了。
using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
public class HttpSend
{
/// <summary>
/// GET下載頁面內容
/// </summary>
/// <param name="url">請求的地址</param>
/// <param name="encoding">內容編碼</param>
/// <returns></returns>
public static string GetPageContent(string url, Encoding encoding)
{
string html=null;
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream ioStream = response.GetResponseStream();
StreamReader sr = new StreamReader(ioStream, encoding);
html = sr.ReadToEnd();
sr.Close();
ioStream.Close();
response.Close();
}
catch (Exception ex) { }
return html;
}
}
//使用
string html=HttpSend.GetPageContent("你的qq oauth地址",Encoding.UTF8);
string key = "\"openid\":\"";
int startIndex = html.IndexOf(key);
if (startIndex != -1)
{
int endIndex = html.IndexOf("\",", startIndex);
string openid = html.Substring(startIndex + key.Length, endIndex - startIndex - key.Length);
Response.Write(openid);
}
else
{//找不到openid,出錯了。。
}