.net 2种后台请求接口并返回数据的方式

第一种(不对请求头做处理):

 1  public Dictionary<string, object> Common_Jdbc(string url, string type) 
 2         {
 3             try
 4             {
 5 
 6                 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
 7                 req.Method = type;
 8                 HttpWebResponse response = null;
 9                 try
10                 {
11                     response = (HttpWebResponse)req.GetResponse();
12                 }
13                 catch (WebException ex)
14                 {
15                     response = (HttpWebResponse)ex.Response;
16                 }                
17                 StreamReader sr2 = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
18                 string strResult =server.UrlDecode(sr2.ReadToEnd());
19                 Dictionary<string, object> dic = this.JsonToDictionary(strResult);
20                 return dic;
21 
22             }
23 
24             catch (Exception ex)
25             {
26                 throw new Exception(ex.Message);
27             
28             }
29         
30         }
View Code

第一种(对请求头设置必要的参数)对header添加认证信息

 public Dictionary<string, object> user_jdbc(string url, string type) 
        {
            try
            {
                HttpSessionState session = HttpContext.Current.Session;
                if (session["access_token"]!= null)
                {
                    string access_token = session["access_token"].ToString();                    
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = type;
                    req.Headers.Add("Authorization", "bearer " + access_token);
                    req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                    req.Accept = "application/json";                  
                    HttpWebResponse response = null;
                    try
                    {
                        response = (HttpWebResponse)req.GetResponse();
                    }
                    catch (WebException ex)
                    {
                        response = (HttpWebResponse)ex.Response;
                    }
                    StreamReader str = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    string strResult = server.UrlDecode(str.ReadToEnd());                    
                    Dictionary<string, object> dic = this.JsonToDictionary(strResult);
                    return dic;

                }
                else 
                {
                    return null;
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            
            }
        
        }
View Code

对第一种方式的后台解析数据: 

  Dictionary<string, object> dic = com.Common_Jdbc(url, "GET");
                if (Convert.ToInt32(dic["code"]) == 200)
                {
                    ArrayList arr = (ArrayList)dic["data"];
                    if (arr.Count > 0)
                    {
                        int con = 0;
                        for (int i = 0; i < arr.Count; i++)
                        {
                              Dictionary<string, object> d = (Dictionary<string, object>)arr[i];
                            Dictionary<string, object> inv = (Dictionary<string, object>)d["aaa"];//d["aaa"]中是包含集合的
//d["bb"] 就是json中bb元素的值, inv["ccc"] 就是inv中ccc元素的值,
//后台拼接html 代码就好了
                         }
View Code

第二种 调用接口的方式:

   string url = "http://test";//测试接口
        HttpClient client = new HttpClient();
        string api_target = "aaa";//方法名称
        string api_key = "bbb";//一般为第三方接口的key
        string api_timespan = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//时间戳
        string api_pass = "********";//一般为第三方接口的密码

        Dictionary<string, object> d = new Dictionary<string, object>();
        d.Add("canshu1", canshu1);
        d.Add("canshu2", canshu2);//接口需要的参数
        JavaScriptSerializer js = new JavaScriptSerializer();
        string api_input = js.Serialize(d);//序列化
        string api_secret = fjw.Utility.Str.StrManage.MD5(api_target + api_key + api_input + api_timespan + api_pass);

        List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
        paramList.Add(new KeyValuePair<string, string>("api_key", api_key));
        paramList.Add(new KeyValuePair<string, string>("api_input", api_input));
        paramList.Add(new KeyValuePair<string, string>("api_target", api_target));
        paramList.Add(new KeyValuePair<string, string>("api_secret", api_secret));
        paramList.Add(new KeyValuePair<string, string>("api_timespan", api_timespan));

        HttpResponseMessage re = client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList)).Result;
        string result = re.Content.ReadAsStringAsync().Result;             
        dynamic modelDy = JsonConvert.DeserializeObject(result); //反序列化
               

        if (modelDy["code"].ToString() == "1")
        {
           string aaa = modelDy["aaa"].ToString();  //json 格式中aaa的值       
            JArray arr = (JArray)modelDy["list"];//list 为一个数据
            rptList.DataSource = arr;
            rptList.DataBind();
}
}
原文地址:https://www.cnblogs.com/flyfengling/p/7325998.html