前言:最近公司项目与外部api接口对接较多 ,写下自己的代码总结。介绍两种访问方式(HttpClient、HttpWebRequest)
一、HttpWebRequest 访问Api
private static string webPost(string url, string obj = null) { string param = (obj);//参数 byte[] bs = Encoding.Default.GetBytes(param); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/json"; req.ContentLength = bs.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); HttpWebResponse response2 = (HttpWebResponse)req.GetResponse(); StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.UTF8); string result = sr2.ReadToEnd(); return result; } }
二、HttpClient访问Api
////// Get请求 /// public string GetToken()
{
try { HttpClient myHttpClient = new HttpClient(); var urlstring = "https://oapi.dingtalk.com/gettoken?appkey=APPKEY&appsecret=APPSECRET"; urlstring = urlstring.Replace("APPKEY", appkey); urlstring = urlstring.Replace("APPSECRET", appsecret); HttpResponseMessage response = myHttpClient.GetAsync(urlstring).Result; var content = response.Content.ReadAsAsync
////// Post请求/// public string getList(long unixstart, long unixend, int cursor, bool start) { try { HttpClient myHttpClient = new HttpClient(); var urlstring = "https://oapi.dingtalk.com/topapi/processinstance/listids?access_token=ACCESS_TOKEN"; urlstring = urlstring.Replace("ACCESS_TOKEN", access_token); var content = new FormUrlEncodedContent(new Dictionary() { { "process_code",""}, { "start_time", }, { "end_time" ,}, { "size" ,"10"}, { "cursor" ,)} }); HttpResponseMessage response = myHttpClient.PostAsync(urlstring, content).Result; var jsonlist = response.Content.ReadAsAsync
三、时间戳与DateTime互转
////// 将c# DateTime时间格式转换为Unix时间戳格式 /// /// ///public long ConvertDateTimeInt(DateTime time) { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); long t = (time.Ticks - startTime.Ticks) / 10000; return t; } /// /// c# Unix时间戳格式转换成DateTime /// /// ///public System.DateTime ConvertIntDateTime(long d) { System.DateTime time = System.DateTime.MinValue; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); time = startTime.AddMilliseconds(d); return time; }