Interface calling code of TV station program table based on C

  • 2021-10-15 11:19:21
  • OfStack

Interface address: http://www.juhe.cn/docs/api/id/129


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xfrog.Net;
using System.Diagnostics;
using System.Web;
 
//----------------------------------
//  Sample code for TV program schedule call   -   Aggregate data 
//  Online interface documentation: http://www.juhe.cn/docs/129
//  In code JsonObject Class download address :http://download.csdn.net/download/gcm3206021155665/7458439
//----------------------------------
 
namespace ConsoleAPI
{
  class Program
  {
    static void Main(string[] args)
    {
      string appkey = "*******************"; // Configure the appkey
 
       
      //1. Classification of TV stations 
      string url1 = "http://japi.juhe.cn/tv/getCategory";
 
      var parameters1 = new Dictionary<string, string>();
 
      parameters1.Add("key", appkey);// You applied for it key
 
      string result1 = sendPost(url1, parameters1, "get");
 
      JsonObject newObj1 = new JsonObject(result1);
      String errorCode1 = newObj1["error_code"].Value;
 
      if (errorCode1 == "0")
      {
        Debug.WriteLine(" Success ");
        Debug.WriteLine(newObj1);
      }
      else
      {
        //Debug.WriteLine(" Failure ");
        Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1["reason"].Value);
      }
 
 
      //2. TV channel list 
      string url2 = "http://japi.juhe.cn/tv/getChannel";
 
      var parameters2 = new Dictionary<string, string>();
 
      parameters2.Add("key", appkey);// You applied for it key
      parameters2.Add("pId" , ""); // Television classification id
 
      string result2 = sendPost(url2, parameters2, "get");
 
      JsonObject newObj2 = new JsonObject(result2);
      String errorCode2 = newObj2["error_code"].Value;
 
      if (errorCode2 == "0")
      {
        Debug.WriteLine(" Success ");
        Debug.WriteLine(newObj2);
      }
      else
      {
        //Debug.WriteLine(" Failure ");
        Debug.WriteLine(newObj2["error_code"].Value+":"+newObj2["reason"].Value);
      }
 
 
      //3. Television program list 
      string url3 = "http://japi.juhe.cn/tv/getProgram";
 
      var parameters3 = new Dictionary<string, string>();
 
      parameters3.Add("key", appkey);// You applied for it key
      parameters3.Add("code" , ""); // Channel code 
      parameters3.Add("date" , ""); // Date ( Format yyyy-MM-dd, The default is the date of the day )
 
      string result3 = sendPost(url3, parameters3, "get");
 
      JsonObject newObj3 = new JsonObject(result3);
      String errorCode3 = newObj3["error_code"].Value;
 
      if (errorCode3 == "0")
      {
        Debug.WriteLine(" Success ");
        Debug.WriteLine(newObj3);
      }
      else
      {
        //Debug.WriteLine(" Failure ");
        Debug.WriteLine(newObj3["error_code"].Value+":"+newObj3["reason"].Value);
      }
 
 
    }
 
    /// <summary>
    /// Http (GET/POST)
    /// </summary>
    /// <param name="url"> Request URL</param>
    /// <param name="parameters"> Request parameter </param>
    /// <param name="method"> Request method </param>
    /// <returns> Response content </returns>
    static string sendPost(string url, IDictionary<string, string> parameters, string method)
    {
      if (method.ToLower() == "post")
      {
        HttpWebRequest req = null;
        HttpWebResponse rsp = null;
        System.IO.Stream reqStream = null;
        try
        {
          req = (HttpWebRequest)WebRequest.Create(url);
          req.Method = method;
          req.KeepAlive = false;
          req.ProtocolVersion = HttpVersion.Version10;
          req.Timeout = 5000;
          req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
          byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
          reqStream = req.GetRequestStream();
          reqStream.Write(postData, 0, postData.Length);
          rsp = (HttpWebResponse)req.GetResponse();
          Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
          return GetResponseAsString(rsp, encoding);
        }
        catch (Exception ex)
        {
          return ex.Message;
        }
        finally
        {
          if (reqStream != null) reqStream.Close();
          if (rsp != null) rsp.Close();
        }
      }
      else
      {
        // Create a request 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
 
        //GET Request 
        request.Method = "GET";
        request.ReadWriteTimeout = 5000;
        request.ContentType = "text/html;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
 
        // Return content 
        string retString = myStreamReader.ReadToEnd();
        return retString;
      }
    }
 
    /// <summary>
    ///  Assemble plain text request parameters. 
    /// </summary>
    /// <param name="parameters">Key-Value Formal request parameter dictionary </param>
    /// <returns>URL Encoded request data </returns>
    static string BuildQuery(IDictionary<string, string> parameters, string encode)
    {
      StringBuilder postData = new StringBuilder();
      bool hasParam = false;
      IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
      while (dem.MoveNext())
      {
        string name = dem.Current.Key;
        string value = dem.Current.Value;
        //  Ignore parameters with empty parameter name or parameter value 
        if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
        {
          if (hasParam)
          {
            postData.Append("&");
          }
          postData.Append(name);
          postData.Append("=");
          if (encode == "gb2312")
          {
            postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
          }
          else if (encode == "utf8")
          {
            postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
          }
          else
          {
            postData.Append(value);
          }
          hasParam = true;
        }
      }
      return postData.ToString();
    }
 
    /// <summary>
    ///  Converts the response stream to text. 
    /// </summary>
    /// <param name="rsp"> Response flow object </param>
    /// <param name="encoding"> Coding mode </param>
    /// <returns> Response text </returns>
    static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    {
      System.IO.Stream stream = null;
      StreamReader reader = null;
      try
      {
        //  Read as a character stream HTTP Response 
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        return reader.ReadToEnd();
      }
      finally
      {
        //  Release resources 
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
      }
    }
  }
}


Related articles: