【Unity】LineのNotifyにunityから画像をHTTP POST送信する方法

【Unity】から  Line notifyに画像をHTTP POST送信する関数です。需要はあまりないとは思いますが、こないだ使おうとして苦労したので載せておきます。

multipartTest(“ご自身のラインNotify用のトークン”);

を実行すれば、画像を送信できます。

linURL = “https://notify-api.line.me/api/notify” です。

  1. public class FormFile {
  2.         public string Name { get; set; }
  3.         public string ContentType { get; set; }
  4.         public string FilePath { get; set; }
  5.         public byte[] bytes { get; set; }
  6.     }
  7.     //ラインメッセージは1時間あたり1000回
  8.     //1時間あたり50枚の画像送信制限
  9.     private void multipartTest(string access_token) {
  10.         Dictionary<string, object> d = new Dictionary<string, object>()
  11.         {
  12.         // message , imageFile … name is provided by LINE API
  13.         { “message”, @”From 3tap ” + fileName },
  14.         { “imageFile”, new FormFile(){ Name = ”ファイル名”, ContentType = “image/jpeg”, FilePath = ”ファイルのパス” }
  15.         }
  16.     };
  17.         string boundary = “Boundary”;
  18.         List<byte[]> output = genMultPart(d, boundary);
  19.         lineNotifyMultipart(access_token, boundary, output);
  20.     }
  21.     private void lineNotifyMultipart(string access_token, string boundary, List<byte[]> output) {
  22.         try {
  23.             #region POST multipart/form-data
  24.             StringBuilder sb = new StringBuilder();
  25.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(lineUrl);
  26.             request.Method = “POST”;
  27.             request.ContentType = “multipart/form-data; boundary=Boundary”;
  28.             request.Timeout = 30000;
  29.             // header
  30.             sb.Clear();
  31.             sb.Append(“Bearer “);
  32.             sb.Append(access_token);
  33.             request.Headers.Add(“Authorization”, sb.ToString());
  34.             // note: multipart/form-data boundary must exist in headers ContentType
  35.             sb.Clear();
  36.             sb.Append(“multipart/form-data; boundary=”);
  37.             sb.Append(boundary);
  38.             request.ContentType = sb.ToString();
  39.             // write Post Body Message
  40.             BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
  41.             foreach (byte[] bytes in output)
  42.                 bw.Write(bytes);
  43.             #endregion
  44.             getResponse(request);
  45.         } catch (Exception ex) {
  46.             Debug.Log(ex.ToString());
  47.             #region Exception
  48.             StringBuilder sbEx = new StringBuilder();
  49.             sbEx.Append(ex.GetType());
  50.             sbEx.AppendLine();
  51.             sbEx.AppendLine(ex.Message);
  52.             sbEx.AppendLine(ex.StackTrace);
  53.             if (ex.InnerException != null)
  54.                 sbEx.AppendLine(ex.InnerException.Message);
  55.             //myException ex2 = new myException(sbEx.ToString());
  56.             //message(ex2.Message);
  57.             #endregion
  58.         }
  59.     }
  60.     private void getResponse(HttpWebRequest request) {
  61.         StringBuilder sb = new StringBuilder();
  62.         StringBuilder limit = new StringBuilder();
  63.         string result = string.Empty;
  64.         StreamReader sr = null;
  65.         try {
  66.             #region Get Response
  67.             if (request == null)
  68.                 return;
  69.             // HttpWebRequest GetResponse() if error happened will trigger WebException
  70.             using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
  71.                 sb.AppendLine();
  72.                 foreach (var x in response.Headers) {
  73.                     sb.Append(x);
  74.                     sb.Append(” : “);
  75.                     sb.Append(response.Headers[x.ToString()]);
  76.                     if (x.ToString() == “X-RateLimit-Reset”) {
  77.                         sb.Append(” ( “);
  78.                         //sb.Append(CheckFormat.ToEpcohDateTimeUTC(long.Parse(response.Headers[x.ToString()])));
  79.                         sb.Append(long.Parse(response.Headers[x.ToString()]));
  80.                         sb.Append(” )”);
  81.                     }
  82.                     sb.AppendLine();
  83.                     //////////////////////////////////////////////////////////////////////////////////////
  84.                     //追加 制限の残り回数と解除する時間を取得
  85.                     if (x.ToString() == “X-RateLimit-Remaining”) {
  86.                         limit.Append(“message limit:”);
  87.                         limit.Append(response.Headers[x.ToString()]);
  88.                         limit.AppendLine();
  89.                     }
  90.                     if (x.ToString() == “X-RateLimit-ImageRemaining”) {
  91.                         limit.Append(“image limit:”);
  92.                         limit.Append(response.Headers[x.ToString()] + “”);
  93.                         limit.AppendLine();
  94.                     }
  95.                     if (x.ToString() == “X-RateLimit-Reset”) {
  96.                         DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  97.                         DateTime time = UnixEpoch.AddSeconds(long.Parse(response.Headers[x.ToString()]));
  98.                         limit.Append(“Reset:” + time);
  99.                         limit.AppendLine();
  100.                     }
  101.                     //////////////////////////////////////////////////////////////////////////////////////
  102.                 }
  103.                 using (sr = new StreamReader(response.GetResponseStream())) {
  104.                     result = sr.ReadToEnd();
  105.                     sb.Append(result);
  106.                 }
  107.             }
  108.             //////////////////////////////////////////////////////////////////////////////////////
  109.             //追加
  110.             limit.AppendLine();
  111.             limit.Append(“Saved in gallery”);
  112.             StartCoroutine(Pop(limit.ToString(), text1));//取得した文字列を表示
  113.             //////////////////////////////////////////////////////////////////////////////////////
  114.             Debug.Log(sb.ToString());
  115.             //message(sb.ToString());
  116.             #endregion
  117.         } catch (WebException ex) {
  118.             #region WebException handle
  119.             // WebException Response
  120.             using (HttpWebResponse response = (HttpWebResponse)ex.Response) {
  121.                 sb.AppendLine(“Error”);
  122.                 foreach (var x in response.Headers) {
  123.                     sb.Append(x);
  124.                     sb.Append(” : “);
  125.                     sb.Append(response.Headers[x.ToString()]);
  126.                     sb.AppendLine();
  127.                 }
  128.                 using (sr = new StreamReader(response.GetResponseStream())) {
  129.                     result = sr.ReadToEnd();
  130.                     sb.Append(result);
  131.                 }
  132.                 //message(sb.ToString());
  133.             }
  134.             #endregion
  135.         }
  136.     }
  137.     public List<byte[]> genMultPart(Dictionary<string, object> parameters, string boundary) {
  138.         StringBuilder sb = new StringBuilder();
  139.         sb.Clear();
  140.         sb.Append(“\r\n–“);
  141.         sb.Append(boundary);
  142.         sb.Append(“\r\n”);
  143.         string beginBoundary = sb.ToString();
  144.         sb.Clear();
  145.         sb.Append(“\r\n–“);
  146.         sb.Append(boundary);
  147.         sb.Append(“–\r\n”);
  148.         string endBoundary = sb.ToString();
  149.         sb.Clear();
  150.         sb.Append(“Content-Type: multipart/form-data; boundary=”);
  151.         sb.Append(boundary);
  152.         sb.Append(“\r\n”);
  153.         List<byte[]> byteList = new List<byte[]>();
  154.         byteList.Add(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
  155.         foreach (KeyValuePair<string, object> pair in parameters) {
  156.             if (pair.Value is FormFile) {
  157.                 byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
  158.                 FormFile form = pair.Value as FormFile;
  159.                 sb.Clear();
  160.                 sb.Append(“Content-Disposition: form-data; name=\””);
  161.                 sb.Append(pair.Key);
  162.                 sb.Append(“\”; filename=\””);
  163.                 sb.Append(form.Name);
  164.                 sb.Append(“\”\r\nContent-Type: “);
  165.                 sb.Append(form.ContentType);
  166.                 sb.Append(“\r\n\r\n”);
  167.                 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
  168.                 byteList.Add(bytes);
  169.                 if (form.bytes == null && !string.IsNullOrEmpty(form.FilePath)) {
  170.                     FileStream fs = new FileStream(form.FilePath, FileMode.Open, FileAccess.Read);
  171.                     MemoryStream ms = new MemoryStream();
  172.                     fs.CopyTo(ms);
  173.                     byteList.Add(ms.ToArray());
  174.                 } else
  175.                     byteList.Add(form.bytes);
  176.             } else {
  177.                 byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
  178.                 sb.Clear();
  179.                 sb.Append(“Content-Disposition: form-data; name=\””);
  180.                 sb.Append(pair.Key);
  181.                 sb.Append(“\””);
  182.                 sb.Append(“\r\n\r\n”);
  183.                 sb.Append(pair.Value);
  184.                 string data = sb.ToString();
  185.                 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
  186.                 byteList.Add(bytes);
  187.             }
  188.         }
  189.         byteList.Add(System.Text.Encoding.ASCII.GetBytes(endBoundary));
  190.         return byteList;
  191.     }

 

 

タイトルとURLをコピーしました