【Unity】から Line notifyに画像をHTTP POST送信する関数です。需要はあまりないとは思いますが、こないだ使おうとして苦労したので載せておきます。
multipartTest(“ご自身のラインNotify用のトークン”);
を実行すれば、画像を送信できます。
linURL = “https://notify-api.line.me/api/notify” です。
- public class FormFile {
- public string Name { get; set; }
- public string ContentType { get; set; }
- public string FilePath { get; set; }
- public byte[] bytes { get; set; }
- }
- //ラインメッセージは1時間あたり1000回
- //1時間あたり50枚の画像送信制限
- private void multipartTest(string access_token) {
- Dictionary<string, object> d = new Dictionary<string, object>()
- {
- // message , imageFile … name is provided by LINE API
- { “message”, @”From 3tap ” + fileName },
- { “imageFile”, new FormFile(){ Name = ”ファイル名”, ContentType = “image/jpeg”, FilePath = ”ファイルのパス” }
- }
- };
- string boundary = “Boundary”;
- List<byte[]> output = genMultPart(d, boundary);
- lineNotifyMultipart(access_token, boundary, output);
- }
- private void lineNotifyMultipart(string access_token, string boundary, List<byte[]> output) {
- try {
- #region POST multipart/form-data
- StringBuilder sb = new StringBuilder();
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(lineUrl);
- request.Method = “POST”;
- request.ContentType = “multipart/form-data; boundary=Boundary”;
- request.Timeout = 30000;
- // header
- sb.Clear();
- sb.Append(“Bearer “);
- sb.Append(access_token);
- request.Headers.Add(“Authorization”, sb.ToString());
- // note: multipart/form-data boundary must exist in headers ContentType
- sb.Clear();
- sb.Append(“multipart/form-data; boundary=”);
- sb.Append(boundary);
- request.ContentType = sb.ToString();
- // write Post Body Message
- BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
- foreach (byte[] bytes in output)
- bw.Write(bytes);
- #endregion
- getResponse(request);
- } catch (Exception ex) {
- Debug.Log(ex.ToString());
- #region Exception
- StringBuilder sbEx = new StringBuilder();
- sbEx.Append(ex.GetType());
- sbEx.AppendLine();
- sbEx.AppendLine(ex.Message);
- sbEx.AppendLine(ex.StackTrace);
- if (ex.InnerException != null)
- sbEx.AppendLine(ex.InnerException.Message);
- //myException ex2 = new myException(sbEx.ToString());
- //message(ex2.Message);
- #endregion
- }
- }
- private void getResponse(HttpWebRequest request) {
- StringBuilder sb = new StringBuilder();
- StringBuilder limit = new StringBuilder();
- string result = string.Empty;
- StreamReader sr = null;
- try {
- #region Get Response
- if (request == null)
- return;
- // HttpWebRequest GetResponse() if error happened will trigger WebException
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
- sb.AppendLine();
- foreach (var x in response.Headers) {
- sb.Append(x);
- sb.Append(” : “);
- sb.Append(response.Headers[x.ToString()]);
- if (x.ToString() == “X-RateLimit-Reset”) {
- sb.Append(” ( “);
- //sb.Append(CheckFormat.ToEpcohDateTimeUTC(long.Parse(response.Headers[x.ToString()])));
- sb.Append(long.Parse(response.Headers[x.ToString()]));
- sb.Append(” )”);
- }
- sb.AppendLine();
- //////////////////////////////////////////////////////////////////////////////////////
- //追加 制限の残り回数と解除する時間を取得
- if (x.ToString() == “X-RateLimit-Remaining”) {
- limit.Append(“message limit:”);
- limit.Append(response.Headers[x.ToString()]);
- limit.AppendLine();
- }
- if (x.ToString() == “X-RateLimit-ImageRemaining”) {
- limit.Append(“image limit:”);
- limit.Append(response.Headers[x.ToString()] + “”);
- limit.AppendLine();
- }
- if (x.ToString() == “X-RateLimit-Reset”) {
- DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- DateTime time = UnixEpoch.AddSeconds(long.Parse(response.Headers[x.ToString()]));
- limit.Append(“Reset:” + time);
- limit.AppendLine();
- }
- //////////////////////////////////////////////////////////////////////////////////////
- }
- using (sr = new StreamReader(response.GetResponseStream())) {
- result = sr.ReadToEnd();
- sb.Append(result);
- }
- }
- //////////////////////////////////////////////////////////////////////////////////////
- //追加
- limit.AppendLine();
- limit.Append(“Saved in gallery”);
- StartCoroutine(Pop(limit.ToString(), text1));//取得した文字列を表示
- //////////////////////////////////////////////////////////////////////////////////////
- Debug.Log(sb.ToString());
- //message(sb.ToString());
- #endregion
- } catch (WebException ex) {
- #region WebException handle
- // WebException Response
- using (HttpWebResponse response = (HttpWebResponse)ex.Response) {
- sb.AppendLine(“Error”);
- foreach (var x in response.Headers) {
- sb.Append(x);
- sb.Append(” : “);
- sb.Append(response.Headers[x.ToString()]);
- sb.AppendLine();
- }
- using (sr = new StreamReader(response.GetResponseStream())) {
- result = sr.ReadToEnd();
- sb.Append(result);
- }
- //message(sb.ToString());
- }
- #endregion
- }
- }
- public List<byte[]> genMultPart(Dictionary<string, object> parameters, string boundary) {
- StringBuilder sb = new StringBuilder();
- sb.Clear();
- sb.Append(“\r\n–“);
- sb.Append(boundary);
- sb.Append(“\r\n”);
- string beginBoundary = sb.ToString();
- sb.Clear();
- sb.Append(“\r\n–“);
- sb.Append(boundary);
- sb.Append(“–\r\n”);
- string endBoundary = sb.ToString();
- sb.Clear();
- sb.Append(“Content-Type: multipart/form-data; boundary=”);
- sb.Append(boundary);
- sb.Append(“\r\n”);
- List<byte[]> byteList = new List<byte[]>();
- byteList.Add(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
- foreach (KeyValuePair<string, object> pair in parameters) {
- if (pair.Value is FormFile) {
- byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
- FormFile form = pair.Value as FormFile;
- sb.Clear();
- sb.Append(“Content-Disposition: form-data; name=\””);
- sb.Append(pair.Key);
- sb.Append(“\”; filename=\””);
- sb.Append(form.Name);
- sb.Append(“\”\r\nContent-Type: “);
- sb.Append(form.ContentType);
- sb.Append(“\r\n\r\n”);
- byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
- byteList.Add(bytes);
- if (form.bytes == null && !string.IsNullOrEmpty(form.FilePath)) {
- FileStream fs = new FileStream(form.FilePath, FileMode.Open, FileAccess.Read);
- MemoryStream ms = new MemoryStream();
- fs.CopyTo(ms);
- byteList.Add(ms.ToArray());
- } else
- byteList.Add(form.bytes);
- } else {
- byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
- sb.Clear();
- sb.Append(“Content-Disposition: form-data; name=\””);
- sb.Append(pair.Key);
- sb.Append(“\””);
- sb.Append(“\r\n\r\n”);
- sb.Append(pair.Value);
- string data = sb.ToString();
- byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
- byteList.Add(bytes);
- }
- }
- byteList.Add(System.Text.Encoding.ASCII.GetBytes(endBoundary));
- return byteList;
- }