之前有分享過兩篇使用Line Notify的機制發送訊息或圖片,沒想到因為有降版開發(4.7–>4.5),突然之間都不行了,花了好多時間DeBug,分析從Line Notify那邊的回應看到,竟然發生了「無法建立 SSL/TLS 的安全通道」,原來Line把TLS1.0、1.1都關掉了,強迫你要用TLS1.2,而恰巧我跑的都不是1.2,那當然就GG了,還好有解,請看下面分享:
原因就在於我開發的程式使用的是.NET framework 4.5,所以要設定 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 語法,強迫使用TLS1.2,當然如果是開發.NET framework 4.5以上的版本,就不會出現這個問題了。
所以之前傳訊息的範例要改成以下才能運作:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // 使用.NET framework 4.5 要加上這一行強迫改用TLS1.2
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "{替換你的權杖金鑰}");
var content = new Dictionary<string, string>();
content.Add("message", "測試訊息");
httpClient.PostAsync("https://notify-api.line.me/api/notify", new FormUrlEncodedContent(content));
發圖片的要改這樣:
private void button1_Click(object sender, EventArgs e)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // 使用.NET framework 4.5 要加上這一行強迫改用TLS1.2
string token = ""; // Please set Token.
string msg = "Notify test";
string ApiUrl = "https://notify-api.line.me/api/notify";
FileStream img = File.OpenRead(@"C:\Windows\Web\Screen\img100.jpg");
var http = new HttpClient();
{
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var body = new MultipartFormDataContent();
body.Add(new StringContent(msg), "message");
if (img != Stream.Null)
{
var imgFile = new StreamContent(img);
body.Add(imgFile, "imageFile", "*");
}
http.PostAsync(ApiUrl, body);
}
}
感謝攻城獅大大的文章,請參考這篇來源。