public String getTempAuthorizeCode() { WebClient webClient = WebClient.instance; String param = Consts.GET_USER_TOKEN_URL + getParams(); try { System.Net.HttpWebResponse httpWebResponse = webClient.getHttpWebResponse(param); String tempUrl = httpWebResponse.GetResponseHeader("Location"); Uri uri = new Uri(tempUrl); string queryString = uri.Query; NameValueCollection col = GetQueryString(queryString); return(col["tempAuthorizeCode"].ToString()); }catch (Exception ex) { if (currentTryRunNum == TRY_AGAIN_MUN) { FailRequestManager.mInstance.saveInFailList(mModel.UserID, Convert.ToDateTime(mSyncDay), param, (ex == null ? "" : ex.Message)); return(null); } else { currentTryRunNum++; return(getTempAuthorizeCode()); } } }
private static string GetHead(string remotefile, string localfile) { string sReturn = ""; try { System.IO.FileStream OutputBin = null; if (!string.IsNullOrEmpty(localfile)) { OutputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile); request.Method = "HEAD"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); byte[] buffer; string output; foreach (string sHeader in response.Headers) { output = sHeader + ":" + response.GetResponseHeader(sHeader); if (!string.IsNullOrEmpty(localfile)) { buffer = System.Text.Encoding.UTF8.GetBytes(output.ToCharArray()); OutputBin.Write(buffer, 0, buffer.Length); } else { Console.WriteLine(output); } } sReturn = response.StatusCode.ToString(); if (sReturn != response.StatusDescription) { sReturn += " " + response.StatusDescription; } response.Close(); } catch (Exception ex1) { sReturn = ex1.Message; } if (!string.IsNullOrEmpty(localfile)) { OutputBin.Close(); OutputBin.Dispose(); } } catch (Exception ex2) { sReturn = ex2.Message; } return(sReturn); }
public RemoteFork.Plugins.BaseItem[] LastModifiedPlayList(string NamePlayList) { string PathFileUpdateTime = System.IO.Path.GetTempPath() + NamePlayList + ".UpdateTime.tmp"; string PathFilePlayList = System.IO.Path.GetTempPath() + NamePlayList + ".PlayList.tmp"; System.Net.WebRequest request = System.Net.WebRequest.Create("http://super-pomoyka.us.to/trash/ttv-list/ttv." + NamePlayList + ".iproxy.m3u?ip=" + IPAdress + ":" + PortAce); request.Method = "HEAD"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)(request.GetResponse()); var responHeader = response.GetResponseHeader("Last-Modified"); response.Close(); System.Net.WebClient WC = new System.Net.WebClient(); WC.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"); WC.Encoding = System.Text.Encoding.UTF8; var items = new System.Collections.Generic.List <RemoteFork.Plugins.BaseItem>(); RemoteFork.Plugins.BaseItem Item = new RemoteFork.Plugins.BaseItem(); if ((System.IO.File.Exists(PathFileUpdateTime) && System.IO.File.Exists(PathFilePlayList)) == false) { UpdatePlayList(NamePlayList, PathFilePlayList, PathFileUpdateTime, responHeader); Item.Type = ItemType.DIRECTORY; Item.Description = WC.DownloadString(PathFilePlayList); items.Add(Item); return(items.ToArray()); } if (responHeader != System.IO.File.ReadAllText(PathFileUpdateTime)) { UpdatePlayList(NamePlayList, PathFilePlayList, PathFileUpdateTime, responHeader); Item.Type = ItemType.DIRECTORY; Item.Description = WC.DownloadString(PathFilePlayList); items.Add(Item); return(items.ToArray()); } Item.Type = ItemType.DIRECTORY; Item.Description = WC.DownloadString(PathFilePlayList); items.Add(Item); return(items.ToArray()); }
private string Download(string fileId, string relatePath) { string url = IPAddress + "/ufInterface?opr=download&filekey=" + fileId + "&hash2=" + HashKey; Uri downUri = new Uri(url); System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(downUri); System.Net.HttpWebResponse myResp = (System.Net.HttpWebResponse)myReq.GetResponse(); string head = myResp.GetResponseHeader("Content-Disposition"); if (head.Trim() == "") { return(""); } int headst = head.IndexOf("filename=\""); int headend = head.IndexOf("\"", headst + 10); string filename = head.Substring(headst + 10, headend - (headst + 10)); filename = System.Web.HttpUtility.UrlDecode(filename); var filepath = Path.Combine(relatePath, filename); using (Stream stream = myReq.GetResponse().GetResponseStream()) { using (FileStream fs = File.Create(@filepath)) { byte[] bytes = new byte[102400]; int n = 1; while (n > 0) { n = stream.Read(bytes, 0, 10240); fs.Write(bytes, 0, n); } fs.Flush(); fs.Close(); } } System.Diagnostics.Debugger.Log(0, fileId, filepath); return(filepath); }
public override async Task <bool> BlobStorageResponseAuthorizedAsync(IOwinContext context, ResourceContext resourceContext, System.Net.HttpWebResponse response) { if (RevokeTokens.Any()) { var tokens = response.GetResponseHeader("x-ms-meta-token"); var missing = RevokeTokens.Where(t => tokens.IndexOf(t) == -1).ToArray(); if (!missing.Any()) { return(true); } var present = await GetTokenIdsAsync(resourceContext.Route.TenantId, resourceContext.Route.Purpose, resourceContext.Route.Resource, null); return(present != null && missing.All(t => present.Contains(t))); //return Task.FromResult(RevokeTokens.All(t => tokens.IndexOf(t) > -1)); } return(await base.BlobStorageResponseAuthorizedAsync(context, resourceContext, response)); }
/// <summary> /// バックグラウンドスレッドでファイルのダウンロードを行う /// </summary> /// <param name="url">ダウンロードするURL</param> /// <param name="downloadToPath">ダウンロード先のディレクトリ名</param> protected void DownloadFile(string url, string downloadToPath) { string downloadFileName = Path.GetFileName(url); downloadFileName = ChangeFileInvalidChar(downloadFileName); string downloadFileFullName = Path.Combine(downloadToPath, downloadFileName); string downloadTempName = downloadFileFullName + ".tmp"; //If-Rangeヘッダに渡すエンティティタグを指定するときは指定する string entityTag = ""; //WebRequestの作成 System.Net.HttpWebRequest webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); //ファイルがあればダウンロードが途中であると判断し、 //ファイルサイズを取得する long firstPos; if (System.IO.File.Exists(downloadTempName)) { firstPos = (new System.IO.FileInfo(downloadTempName)).Length; } else { firstPos = 0; } if (firstPos > 0) { //バイトレンジを指定する webreq.AddRange((int)firstPos); //If-Rangeヘッダを追加 if (!string.IsNullOrEmpty(entityTag)) { webreq.Headers.Add("If-Range", entityTag); } } //そのほかのヘッダを指定する webreq.KeepAlive = false; webreq.Headers.Add("Pragma", "no-cache"); webreq.Headers.Add("Cache-Control", "no-cache"); System.Net.HttpWebResponse webres = null; try { //サーバーからの応答を受信するためのWebResponseを取得 webres = (System.Net.HttpWebResponse)webreq.GetResponse(); } catch (System.Net.WebException e) { //HTTPプロトコルエラーを捕捉し、内容を表示する if (e.Status == System.Net.WebExceptionStatus.ProtocolError) { System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse)e.Response; Console.WriteLine(errres.StatusCode); Console.WriteLine(errres.StatusDescription); } else { Console.WriteLine(e.Message); } webres.Close(); throw new ApplicationException("データ取得エラー", e); } //エンティティタグの表示 Console.WriteLine("ETag:" + webres.GetResponseHeader("ETag")); System.IO.Stream strm = null; System.IO.FileStream fs = null; try { //応答データを受信するためのStreamを取得 strm = webres.GetResponseStream(); //ファイルに書き込むためのFileStreamを作成 fs = new System.IO.FileStream(downloadTempName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); //ファイルに書き込む位置を決定する //206Partial Contentステータスコードが返された時はContent-Rangeヘッダを調べる //それ以外のときは、先頭から書き込む long seekPos = 0; if (webres.StatusCode == System.Net.HttpStatusCode.PartialContent) { string contentRange = webres.GetResponseHeader("Content-Range"); System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match( contentRange, @"bytes\s+(?:(?<first>\d*)-(?<last>\d*)|\*)/(?:(?<len>\d+)|\*)"); if (string.IsNullOrEmpty(m.Groups["first"].Value)) { seekPos = 0; } else { seekPos = int.Parse(m.Groups["first"].Value); } } else { // すでにファイルがある場合にはファイルを削除 fs.Close(); fs.Dispose(); File.Delete(downloadTempName); fs = new System.IO.FileStream(downloadTempName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); } // 途中からのダウンロードにあわせて 書き込み開始位置を変更する fs.SetLength(seekPos); fs.Position = seekPos; //応答データをファイルに書き込む byte[] readData = new byte[1024 * 10]; int readSize = 0; long readDataLength = 0; for (; ;) { readSize = strm.Read(readData, 0, readData.Length); if (readSize == 0) { break; } fs.Write(readData, 0, readSize); readDataLength += readSize; this.InvokeDownloadStatus(url, readDataLength.ToString() + "/" + webres.ContentLength.ToString()); } } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (strm != null) { strm.Close(); strm.Dispose(); } if (webres != null) { webres.Close(); } } // ダウンロードファイルの移動 string bakFile = downloadFileFullName + ".bak"; if (File.Exists(bakFile)) { File.Delete(bakFile); } if (File.Exists(downloadFileFullName)) { File.Move(downloadFileFullName, bakFile); } File.Move(downloadTempName, downloadFileFullName); this.InvokeDownloadStatus(url, "complate"); WriteDownloadUrlLog(downloadToPath + "\\complate.log", url); }
private void DownloadComplete(WebDownload downloadInfo) { // Log.Write(Log.Levels.Debug+1, "GSDR", "Download completed for " + downloadInfo.Url); try { downloadInfo.Verify(); //m_quadTile.QuadTileSet.NumberRetries = 0; // Rename temp file to real name File.Delete(m_localFilePath); File.Move(downloadInfo.SavedFilePath, m_localFilePath); // Make the quad tile reload the new image m_quadTile.DownloadRequests.Remove(this); // ### ??!?? m_quadTile.Initialize(); } catch (System.Net.WebException caught) { System.Net.HttpWebResponse response = caught.Response as System.Net.HttpWebResponse; /* * null response */ if (response == null) { m_quadTile.QuadTileSet.RecordFailedRequest(this); } /* 4xx - Client error * 400 Bad Request * 401 Unauthorized * 403 Forbidden * 404 Not Found * 206 Partial Content * 200 OK && Content length == 0 */ else if (response.StatusCode == System.Net.HttpStatusCode.NotFound || response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden || response.StatusCode == System.Net.HttpStatusCode.BadRequest || response.StatusCode == System.Net.HttpStatusCode.PartialContent || (response.StatusCode == System.Net.HttpStatusCode.OK && response.ContentLength == 0)) { m_quadTile.QuadTileSet.RecordFailedRequest(this); } /* * 5xx - Server Error * 500 Internal Server Error * 501 Not Implemented * 502 Bad Gateway * 503 Service Unavailable */ else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError || response.StatusCode == System.Net.HttpStatusCode.NotImplemented || response.StatusCode == System.Net.HttpStatusCode.BadGateway || response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable ) { //server problem, directly start timeout for the layer, rather than counter per tile TimeSpan waitTime = TimeSpan.FromSeconds(120); //if retry-after is specified then wait for that length of time before retrying String retryAfter = response.GetResponseHeader("Retry-After"); if (retryAfter != null && !retryAfter.Equals(String.Empty)) { Log.Write(Log.Levels.Verbose, "GSDR", "Retry-After response header " + retryAfter); try { //try to convert double retryAfterNumber = Convert.ToDouble(retryAfter); waitTime = TimeSpan.FromSeconds(retryAfterNumber); } catch (System.FormatException fe) { //ignore retry-after, just wait for 60 seconds } } //wait before retrying m_quadTile.QuadTileSet.setTimeoutAndWait(waitTime); } } catch { using (File.Create(m_localFilePath + ".txt")) {} if (File.Exists(downloadInfo.SavedFilePath)) { try { File.Delete(downloadInfo.SavedFilePath); } catch (Exception e) { Log.Write(Log.Levels.Error, "GSDR", "could not delete file " + downloadInfo.SavedFilePath + ":"); Log.Write(e); } } } finally { if (download != null) { download.IsComplete = true; } m_quadTile.QuadTileSet.RemoveFromDownloadQueue(this); // potential deadlock! -step // Immediately queue next download m_quadTile.QuadTileSet.ServiceDownloadQueue(); } }
private static string GetPropfind(string remotefile, string localfile) { string sReturn = ""; try { System.IO.FileStream OutputBin = null; if (!string.IsNullOrEmpty(localfile)) { OutputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile); request.Method = "PROPFIND"; request.Headers.Add("Depth:0"); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); byte[] buffer1; string output; foreach (string sHeader in response.Headers) { output = sHeader + ":" + response.GetResponseHeader(sHeader); if (!string.IsNullOrEmpty(localfile)) { buffer1 = System.Text.Encoding.UTF8.GetBytes(output.ToCharArray()); OutputBin.Write(buffer1, 0, buffer1.Length); } else { Console.WriteLine(output); } } System.IO.Stream dataStream = response.GetResponseStream(); byte[] buffer = new byte[32768]; int read; while ((read = dataStream.Read(buffer, 0, buffer.Length)) > 0) { if (!string.IsNullOrEmpty(localfile)) { OutputBin.Write(buffer, 0, read); } else { Console.Write(System.Text.Encoding.UTF8.GetString(buffer).ToCharArray(), 0, read); } } dataStream.Close(); sReturn = response.StatusCode.ToString(); if (sReturn != response.StatusDescription) { sReturn += " " + response.StatusDescription; } response.Close(); } catch (Exception ex1) { sReturn = ex1.Message; } if (!string.IsNullOrEmpty(localfile)) { OutputBin.Close(); OutputBin.Dispose(); } } catch (Exception ex2) { sReturn = ex2.Message; } return(sReturn); }
void webclientThread(object o) { //webclientSignal.WaitOne(); //#if !NODEPLOY System.Threading.Thread.Sleep(30000); // return; //#endif try { string appHost = new Uri(EnvironmentConfig.App1Url).Host; System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(EnvironmentConfig.App1Url); req.Method = "GET"; System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse(); byte[] resRaw = null; if (res.StatusCode == System.Net.HttpStatusCode.OK) { if (res.ContentLength > 0) { System.IO.Stream io = res.GetResponseStream(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { int data = -1; do { data = io.ReadByte(); if (data == -1) { break; } ms.WriteByte((byte)data); } while (data != -1); resRaw = ms.ToArray(); } } } else { throw new Exception(); } if (resRaw != null) { Encoding.UTF8.GetString(resRaw); } { req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(res.ResponseUri); req.Method = "POST"; req.AllowAutoRedirect = false; req.Referer = res.ResponseUri.ToString(); req.Accept = "text/html, application/xhtml+xml, */*"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"; req.ContentType = "application/x-www-form-urlencoded"; string auth = "UserName="******"&Password="******"&AuthMethod=FormsAuthentication"; req.GetRequestStream().Write(Encoding.UTF8.GetBytes(auth), 0, auth.Length); req.GetRequestStream().Close(); res = (System.Net.HttpWebResponse)req.GetResponse(); } resRaw = null; if (res.ContentLength > 0) { System.IO.Stream io = res.GetResponseStream(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { int data = -1; do { data = io.ReadByte(); if (data == -1) { break; } ms.WriteByte((byte)data); } while (data != -1); resRaw = ms.ToArray(); } } if (resRaw != null) { Encoding.UTF8.GetString(resRaw); } if (res.StatusCode == System.Net.HttpStatusCode.Found) { using (System.Net.Sockets.TcpClient tc = new System.Net.Sockets.TcpClient(EnvironmentConfig.ADFSFamrDNSName, Constraints.HTTPSServiceDefaultPort)) { using (System.Net.Security.SslStream ssl = new SslStream(tc.GetStream(), true)) { ssl.AuthenticateAsClient(EnvironmentConfig.ADFSFamrDNSName, null, System.Security.Authentication.SslProtocols.Default, false); HttpRequest hr = new HttpRequest(HttpRequest.HttpMethod.GET, res.ResponseUri.PathAndQuery); hr.SetHeaderField(System.Net.HttpRequestHeader.Accept, "text/html, application/xhtml+xml, */*"); hr.SetHeaderField(System.Net.HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"); hr.SetHeaderField(System.Net.HttpRequestHeader.Referer, res.GetResponseHeader("location")); string cookStr = res.GetResponseHeader("Set-Cookie"); string[] cookParts = cookStr.Split(new string[] { "=", ";" }, StringSplitOptions.RemoveEmptyEntries); hr.SetHeaderField(System.Net.HttpRequestHeader.Cookie, cookParts[0] + "=" + cookParts[1] + "="); hr.SetHeaderField(System.Net.HttpRequestHeader.AcceptEncoding, "gzip, deflate"); hr.SetHeaderField(System.Net.HttpRequestHeader.Host, EnvironmentConfig.ADFSFamrDNSName); ssl.Write(Encoding.UTF8.GetBytes(hr.ToString())); System.Threading.Thread.Sleep(2000); byte[] temp = null; if (tc.Available > 0) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { while (tc.Available > 0) { byte[] buf = new byte[8192]; int len = ssl.Read(buf, 0, buf.Length); if (len == 0) { break; } ms.Write(buf, 0, len); } temp = ms.ToArray(); } } if (temp != null) { string txt = Encoding.UTF8.GetString(temp); HttpResponse hres = new HttpResponse(); hres.Parse(txt); if (hres.StatusCode != System.Net.HttpStatusCode.TemporaryRedirect) { throw new Exception(); } using (System.Net.Sockets.TcpClient apTc = new System.Net.Sockets.TcpClient(appHost, Constraints.HTTPSServiceDefaultPort)) { using (System.Net.Security.SslStream apSsl = new SslStream(apTc.GetStream(), true)) { try { apSsl.AuthenticateAsClient(appHost, null, System.Security.Authentication.SslProtocols.Default, false); string url = new Uri(hres.GetHeaderFieldValue(System.Net.HttpResponseHeader.Location)).PathAndQuery; HttpRequest hreq = new HttpRequest(HttpRequest.HttpMethod.GET, url); hreq.SetHeaderField(System.Net.HttpRequestHeader.Referer, res.GetResponseHeader("location")); hreq.SetHeaderField(System.Net.HttpRequestHeader.Host, appHost); apSsl.Write(Encoding.UTF8.GetBytes(hreq.ToString())); System.Threading.Thread.Sleep(2000); temp = null; if (apTc.Available > 0) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { while (apTc.Available > 0) { byte[] buf = new byte[8192]; int len = apSsl.Read(buf, 0, buf.Length); if (len == 0) { break; } ms.Write(buf, 0, len); } temp = ms.ToArray(); } } } catch { } if (temp != null) { txt = Encoding.UTF8.GetString(temp); } } } } } } req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(res.GetResponseHeader("Location")); req.Method = "GET"; req.AllowAutoRedirect = false; string c*k = res.GetResponseHeader("Set-Cookie"); string[] cokParts = c*k.Split(new string[] { "=", ";" }, StringSplitOptions.RemoveEmptyEntries); req.Accept = "text/html, application/xhtml+xml, */*"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"; req.CookieContainer = new System.Net.CookieContainer(); System.Net.Cookie cook = new System.Net.Cookie(cokParts[0], cokParts[1], cokParts[3], req.RequestUri.Host); cook.HttpOnly = true; cook.Secure = true; cook.Domain = req.RequestUri.Host; cook.Discard = true; req.CookieContainer.Add(cook); req.Referer = res.GetResponseHeader("Location"); req.Host = req.RequestUri.Host; res = (System.Net.HttpWebResponse)req.GetResponse(); } else { throw new Exception(); } resRaw = null; if (res.ContentLength > 0) { System.IO.Stream io = res.GetResponseStream(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { int data = -1; do { data = io.ReadByte(); if (data == -1) { break; } ms.WriteByte((byte)data); } while (data != -1); resRaw = ms.ToArray(); } } if (resRaw != null) { Encoding.UTF8.GetString(resRaw); } { if (res.StatusCode == System.Net.HttpStatusCode.TemporaryRedirect) { req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(res.GetResponseHeader("Location")); req.Method = "GET"; req.CookieContainer = new System.Net.CookieContainer(); foreach (System.Net.Cookie c*k in res.Cookies) { req.CookieContainer.Add(c*k); } res = (System.Net.HttpWebResponse)req.GetResponse(); } else { throw new Exception(); } } { } } catch { } }
/// <summary> /// 下载保存多媒体文件,返回多媒体保存路径 /// </summary> /// <param name="ACCESS_TOKEN">ACCESS_TOKEN</param> /// <param name="MEDIA_ID">MEDIA_ID</param> /// <param name="physicalFolder">物理文件夹</param> /// <param name="fileName">保存文件名</param> /// <param name="fileSize">文件大小</param> /// <returns>多媒体保存路径</returns> private static string DownloadMultimedia(string ACCESS_TOKEN, string MEDIA_ID, string physicalFolder, string fileName, out long fileSize) { //LogHelper.Save("DownloadMultimedia > " + "ACCESS_TOKEN=" + ACCESS_TOKEN + ",MEDIA_ID=" + MEDIA_ID + ",physicalFolder=" + physicalFolder + ",fileName=" + fileName, "DownloadMultimedia", LogType.Common, LogTime.day); fileSize = 0; string file = string.Empty; string content = string.Empty; string strpath = string.Empty; string savepath = string.Empty; string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + ACCESS_TOKEN + "&media_id=" + MEDIA_ID; string suffixName = string.Empty; System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(stUrl); req.Method = "GET"; using (System.Net.WebResponse wr = req.GetResponse()) { System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)req.GetResponse(); strpath = myResponse.ResponseUri.ToString(); fileSize = myResponse.ContentLength; string _filename = Common.Replace(myResponse.GetResponseHeader("Content-disposition"), ".*filename=\"", "").Trim(new Char[] { '"' }); suffixName = System.IO.Path.GetExtension(_filename).ToLower(); //LogHelper.Save("接收信息:" + "StatusCode=" + myResponse.StatusCode.ToString() + ",StatusDescription=" + myResponse.StatusDescription + ",ContentType=" + myResponse.ContentType + ",Content-disposition=" + myResponse.GetResponseHeader("Content-disposition") + ",filename=" + _filename + ",suffixName=" + suffixName, "DownloadMultimedia", LogType.Common, LogTime.day); physicalFolder = Common.Replace(physicalFolder, @"[\\\s]+$", "") + "\\"; if (!System.IO.Directory.Exists(physicalFolder)) { try { System.IO.Directory.CreateDirectory(physicalFolder); } catch (Exception Ex) { LogHelper.Save("DownloadMultimedia > 创建文件路径失败!physicalFolder=" + physicalFolder, "DownloadMultimedia", LogType.Common, LogTime.day); throw Ex; } } if (string.IsNullOrWhiteSpace(suffixName)) { switch (myResponse.ContentType) { case "image/jpeg": suffixName = ".jpg"; break; case "application/x-jpg": suffixName = ".jpg"; break; case "image/png": suffixName = ".png"; break; case "application/x-png": suffixName = ".png"; break; case "audio/amr": suffixName = ".amr"; break; case "audio/mp3": suffixName = ".mp3"; break; case "video/mp4": suffixName = ".mp4"; break; default: suffixName = !string.IsNullOrWhiteSpace(suffixName) ? suffixName : ".jpg"; break; } } fileName = !string.IsNullOrWhiteSpace(fileName) ? (fileName + suffixName) : !string.IsNullOrWhiteSpace(_filename) ? _filename : (DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + suffixName); savepath = physicalFolder + fileName; System.Net.WebClient mywebclient = new System.Net.WebClient(); //LogHelper.Save("下载到路径:" + savepath, "DownloadMultimedia", LogType.Common, LogTime.day); try { mywebclient.DownloadFile(strpath, savepath); file = savepath; } catch (Exception Ex) { savepath = Ex.ToString(); throw Ex; } } return(file); }
public string GetResponseHeader(string headerName) { return(_webResponse.GetResponseHeader(headerName)); }
/* * string fileName = ""; * long fileSize; * string contentType; * var bytes = WeChatHelper4Net.Multimedia.GetForeverMultimediaStream(accessToken, mediaId, ref fileName, out fileSize, out contentType); * ClassLib4Net.LogHelper.Save("mediaId=" + mediaId + ",bytes.Length=" + bytes.Length + ",fileName=" + fileName + ",fileSize=" + fileSize + ",contentType=" + contentType, nameof(QRCodeController), ClassLib4Net.LogType.Common, ClassLib4Net.LogTime.hour); * System.IO.Stream _stream = new System.IO.MemoryStream(bytes); * _stream.Seek(0, System.IO.SeekOrigin.Begin); * ClassLib4Net.LogHelper.Save("mediaId=" + mediaId + ",_stream.Length=" + _stream.Length + ",fileName=" + fileName + ",fileSize=" + fileSize + ",contentType=" + contentType, nameof(QRCodeController), ClassLib4Net.LogType.Common, ClassLib4Net.LogTime.hour); */ /// <summary> /// 获取永久素材(除了图文,视频) /// 公众号的素材库保存总数量有上限:图文消息素材、图片素材上限为5000,其他类型为1000。 /// 素材的格式大小等要求与公众平台官网一致: /// 图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式 /// 语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式 /// 视频(video):10MB,支持MP4格式 /// 缩略图(thumb):64KB,支持JPG格式 /// </summary> /// <param name="ACCESS_TOKEN">访问令牌</param> /// <param name="MEDIA_ID"></param> /// <param name="fileName"></param> /// <param name="fileSize"></param> /// <param name="contentType"></param> /// <returns></returns> public static byte[] GetForeverMultimediaStream(string ACCESS_TOKEN, string MEDIA_ID, ref string fileName, out long fileSize, out string contentType) { //LogHelper.Save("GetForeverMultimediaStream > " + "ACCESS_TOKEN=" + ACCESS_TOKEN + ",MEDIA_ID=" + MEDIA_ID + ",fileName=" + fileName, nameof(Multimedia), LogType.Common, LogTime.day); fileSize = 0; contentType = ""; string strpath = string.Empty; string stUrl = Common.ApiUrl + "material/get_material?access_token=" + ACCESS_TOKEN; var jsonString = "{\"media_id\":\"" + MEDIA_ID + "\"}"; byte[] bytes = Encoding.UTF8.GetBytes(jsonString); string suffixName = string.Empty; System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(stUrl); req.Method = "POST"; req.Timeout = 30000; req.KeepAlive = true; req.ContentLength = bytes.Length; req.GetRequestStream().Write(bytes, 0, bytes.Length); try { using (System.Net.WebResponse wr = req.GetResponse()) { System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)req.GetResponse(); strpath = myResponse.ResponseUri.ToString(); fileSize = myResponse.ContentLength; contentType = myResponse.ContentType; string _filename = Common.Replace(myResponse.GetResponseHeader("Content-disposition"), ".*filename=\"", "").Trim(new Char[] { '"' }); suffixName = System.IO.Path.GetExtension(_filename).ToLower(); //LogHelper.Save("接收信息:" + "StatusCode=" + myResponse.StatusCode.ToString() + ",StatusDescription=" + myResponse.StatusDescription + ",ContentType=" + myResponse.ContentType + ",Content-disposition=" + myResponse.GetResponseHeader("Content-disposition") + ",filename=" + _filename + ",suffixName=" + suffixName, nameof(Multimedia), LogType.Common, LogTime.day); //接收信息:StatusCode=OK,StatusDescription=OK,ContentType=,Content-disposition=attachment; filename="8a125212e0a52c0c59d6cabcd2de18e8.jpg",filename=8a125212e0a52c0c59d6cabcd2de18e8.jpg,suffixName=.jpg if (string.IsNullOrWhiteSpace(suffixName) && !string.IsNullOrWhiteSpace(contentType)) { suffixName = GetSuffixNameByContentType(contentType); } else if (!string.IsNullOrWhiteSpace(suffixName) && string.IsNullOrWhiteSpace(contentType)) { contentType = GetContentTypeBySuffixName(suffixName); } if (string.IsNullOrWhiteSpace(suffixName) && string.IsNullOrWhiteSpace(contentType)) { if ("CropImage" == _filename) { suffixName = ".jpg"; contentType = GetContentTypeBySuffixName(suffixName); fileName = "CropImage"; } else if (!string.IsNullOrWhiteSpace(fileName)) { suffixName = System.IO.Path.GetExtension(fileName).ToLower(); contentType = GetContentTypeBySuffixName(suffixName); fileName = System.IO.Path.GetFileNameWithoutExtension(fileName); } } fileName = !string.IsNullOrWhiteSpace(fileName) ? (fileName + suffixName) : !string.IsNullOrWhiteSpace(_filename) ? _filename : (MEDIA_ID + suffixName); //将输出流转换字节数组并返回 using (var rs = myResponse.GetResponseStream()) { using (var ms = new MemoryStream()) { rs.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream byte[] rsBytes = new byte[buffsize]; ms.Read(rsBytes, 0, buffsize); return(rsBytes); } } } } catch (Exception ex) { //LogHelper.Save(ex, "ACCESS_TOKEN=" + ACCESS_TOKEN + ",MEDIA_ID=" + MEDIA_ID, nameof(Multimedia), LogTime.day); throw ex; } }
/* * c# 将byte数组保存成图片 * 将byte数组保存成图片: * * 方式一:System.IO.File.WriteAllBytes(@"c:\test.jpg", bytes); * * 方式二:MemoryStream ms=new MemoryStream(Byte[] b); 把那个byte[]数组传进去,然后 * FileStream fs=new FileStream(路径 例如:"E:\image\1.jpg"); * ms.writeto(fs); * ms.close(); * fs.close(); * * 方法三: * * //得到图片地址 * var stringFilePath = context.Server.MapPath(string.Format("~/Image/{0}{1}.jpg", imageName, id)); * //声明一个FileStream用来将图片暂时放入流中 * FileStream stream = new FileStream(stringFilePath, FileMode.Open); * using (stream) * { * //透过GetImageFromStream方法将图片放入byte数组中 * byte[] imageBytes = this.GetImageFromStream(stream,context); * //上下文确定写到客户短时的文件类型 * context.Response.ContentType = "image/jpeg"; * //上下文将imageBytes中的数据写到前段 * context.Response.BinaryWrite(imageBytes); * stream.Close(); * } */ /// <summary> /// 获取临时素材(除了图文,视频,语音) /// 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)。请注意,视频文件不支持https下载,调用该接口需http协议。本接口即为原“下载多媒体文件”接口。 /// </summary> /// <param name="ACCESS_TOKEN">访问令牌</param> /// <param name="MEDIA_ID"></param> /// <param name="fileName"></param> /// <param name="fileSize"></param> /// <param name="contentType"></param> /// <returns></returns> public static byte[] GetTempMultimediaStream(string ACCESS_TOKEN, string MEDIA_ID, ref string fileName, out long fileSize, out string contentType) { //LogHelper.Save("GetTempMultimediaStream > " + "ACCESS_TOKEN=" + ACCESS_TOKEN + ",MEDIA_ID=" + MEDIA_ID + ",fileName=" + fileName, nameof(Multimedia), LogType.Common, LogTime.day); fileSize = 0; contentType = ""; string strpath = string.Empty; string stUrl = Common.ApiUrl + string.Format("media/get?access_token={0}&media_id={1}", ACCESS_TOKEN, MEDIA_ID); string suffixName = string.Empty; System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(stUrl); req.Method = "GET"; req.Timeout = 30000; req.KeepAlive = true; try { using (System.Net.WebResponse wr = req.GetResponse()) { System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)req.GetResponse(); strpath = myResponse.ResponseUri.ToString(); fileSize = myResponse.ContentLength; contentType = myResponse.ContentType; string _filename = Common.Replace(myResponse.GetResponseHeader("Content-disposition"), ".*filename=\"", "").Trim(new Char[] { '"' }); suffixName = System.IO.Path.GetExtension(_filename).ToLower(); //LogHelper.Save("接收信息:" + "StatusCode=" + myResponse.StatusCode.ToString() + ",StatusDescription=" + myResponse.StatusDescription + ",ContentType=" + myResponse.ContentType + ",Content-disposition=" + myResponse.GetResponseHeader("Content-disposition") + ",filename=" + _filename + ",suffixName=" + suffixName, nameof(Multimedia), LogType.Common, LogTime.day); //接收信息:StatusCode=OK,StatusDescription=OK,ContentType=image/jpeg,Content-disposition=attachment; filename="-zu3wS2bJFqRKMonF0CrbEBvnCtKCS7NPyHAvdUIh1rowBDclir9sPP5s1QSBHGT.jpg",filename=-zu3wS2bJFqRKMonF0CrbEBvnCtKCS7NPyHAvdUIh1rowBDclir9sPP5s1QSBHGT.jpg,suffixName=.jpg if (string.IsNullOrWhiteSpace(suffixName) && !string.IsNullOrWhiteSpace(contentType)) { suffixName = GetSuffixNameByContentType(contentType); } else if (!string.IsNullOrWhiteSpace(suffixName) && string.IsNullOrWhiteSpace(contentType)) { contentType = GetContentTypeBySuffixName(suffixName); } if (string.IsNullOrWhiteSpace(suffixName) && string.IsNullOrWhiteSpace(contentType)) { if ("CropImage" == _filename) { suffixName = ".jpg"; contentType = GetContentTypeBySuffixName(suffixName); fileName = "CropImage"; } else if (!string.IsNullOrWhiteSpace(fileName)) { suffixName = System.IO.Path.GetExtension(fileName).ToLower(); contentType = GetContentTypeBySuffixName(suffixName); fileName = System.IO.Path.GetFileNameWithoutExtension(fileName); } } fileName = !string.IsNullOrWhiteSpace(fileName) ? (fileName + suffixName) : !string.IsNullOrWhiteSpace(_filename) ? _filename : (MEDIA_ID + suffixName); //将输出流转换字节数组并返回 using (var rs = myResponse.GetResponseStream()) { using (var ms = new MemoryStream()) { rs.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream byte[] rsBytes = new byte[buffsize]; ms.Read(rsBytes, 0, buffsize); return(rsBytes); } } } } catch (Exception ex) { //LogHelper.Save(ex, "ACCESS_TOKEN=" + ACCESS_TOKEN + ",MEDIA_ID=" + MEDIA_ID, nameof(Multimedia), LogTime.day); throw ex; } }