實用程式系列
筆者這次要介紹服務是比較常用的LineNotify服務,因為往往很簡單的東西,許多人其實會非常瞧不起它,如果發揮創意的話,其實它的特性就會相當好用,也很強大!
筆者會常用在
1.系統通知服務(懶人自動化)
2.股價機器人通知
來體驗一下它的流程吧!
其實這一段API調用也是很簡易,寫法如下:
public class LineNotifyService
{
public async Task<HttpResponseMessage> CallLineNotifyApi(string token, string message)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://notify-api.line.me/api/notify");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var form = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("message", message)
});
return await client.PostAsync("", form);
}
}
//void CallLineNotifyApi(string token)
//{
// var enc = Encoding.UTF8;
// var payload = "message=" + HttpUtility.UrlEncode("測試!", enc);
// using (var wc = new WebClient())
// {
// wc.Encoding = enc;
// wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// wc.Headers.Add("Authorization", "Bearer " + token);
// var response = wc.UploadString(lineUrl, payload);
// }
//}
}
最後我要進行幾個測試情境調用,開始進行測試嚕!
public class LineNotifyServiceTest
{
private string myToken = "";
[SetUp]
public void Setup()
{
}
[Test]
public async Task CallLineNotifyApi_Success_ReturnStatus200()
{
LineNotifyService _lineNotifyService = new LineNotifyService();
var result = await _lineNotifyService.CallLineNotifyApi(myToken, "test");
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
}
[Test]
public async Task CallLineNotifyApi_Unauthorized_ReturnStatus401()
{
LineNotifyService _lineNotifyService = new LineNotifyService();
var result = await _lineNotifyService.CallLineNotifyApi("", "test");
Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode);
}
}
其實這個功能實用性滿高的,假設未來開始進行副業的IT人,可以進一步思考怎麼打造自己產品系統,強化它是真的滿好的。
元哥的筆記