public void TestMultipart() { MultiPart parts; using (MemoryStream stream = new MemoryStream(exampleBytes)) { parts = MultiPart.Parse(stream); } foreach (MultiPartSection section in parts.Sections) { System.Console.WriteLine("New Section"); System.Console.WriteLine($"FileName: {section.FileName}"); System.Console.WriteLine($"Name: {section.Name}"); System.Console.WriteLine($"Content-Type: {section.ContentType}"); System.Console.WriteLine($"Content: {section.DataAsString}"); System.Console.WriteLine("-------------------"); } Assert.AreEqual(3, parts.Sections.Count, "Not the correct amount of sections"); Assert.IsNotNull(parts.Sections.FirstOrDefault(x => x.Name == "text"), "Missing Section"); Assert.IsNotNull(parts.Sections.FirstOrDefault(x => x.Name == "file1"), "Missing Section"); Assert.IsNotNull(parts.Sections.FirstOrDefault(x => x.Name == "file2"), "Missing Section"); Assert.AreEqual(section1Data, parts.Sections.FirstOrDefault(x => x.Name == "text")?.DataAsString, "Incorrect data"); Assert.AreEqual(section2Data, parts.Sections.FirstOrDefault(x => x.Name == "file1")?.DataAsString, "Incorrect data"); Assert.AreEqual(section3Data, parts.Sections.FirstOrDefault(x => x.Name == "file2")?.DataAsString, "Incorrect data"); }
private List <string> GetSubPartList(IPart rootPart) { List <string> list = new List <string>(); switch (rootPart.Type) { case EPartType.Multi: { MultiPart part = rootPart as MultiPart; if (part != null) { foreach (IPart part2 in part.Parts) { list.AddRange(this.GetSubPartList(part2)); } } return(list); } case EPartType.Content: return(list); } list.Add(this._message.GetPartIndex(rootPart)); return(list); }
public static MultiPart CreateFile(string name, string fieldName, string contentType, byte[] content, byte[] eol, Encoding encoding = null) { var parameters = MultiPartParameters.CreateFile(name, fieldName, contentType, eol); var part = new MultiPart(parameters, eol, encoding); part.m_Content = content; return(part); }
public static MultiPart CreateField(string fieldName, string fieldValue, byte[] eol, Encoding encoding = null) { var parameters = MultiPartParameters.CreateField(fieldName, eol); var part = new MultiPart(parameters, eol, encoding); part.m_Content = part.m_Encoding.GetBytes(fieldValue); part.m_ContentString = fieldValue; return(part); }
private void parseStreamWithBoundary() { string fullBoundary = new string(HYPHEN_CHAR, 2) + m_Boundary; foreach (var segment in StreamHelpers.StreamSplitNew(m_Stream, m_Encoding.GetBytes(fullBoundary))) { var part = MultiPart.Parse(segment.Item1, segment.Item2, m_Encoding); m_Parts.Add(part); } }
public static MultiPart Parse(byte[] buf, int length, Encoding encoding = null) { var p = new MultiPart(encoding); if (buf[0] == LF) { p.m_EOL = EOL_LF_BYTES; } else if (buf[0] == CR && buf[1] == LF) { p.m_EOL = EOL_CRLF_BYTES; } else { throw new NFXException(StringConsts.MULTIPART_NO_LF_NOR_CRLF_ISNT_FOUND_ERROR + typeof(MultiPart).Name + ".Parse"); } int eolLength = p.m_EOL.Length; int doubleEOLLength = eolLength << 1; byte[] doubleEOL = new byte[doubleEOLLength]; Array.Copy(p.m_EOL, 0, doubleEOL, 0, eolLength); Array.Copy(p.m_EOL, 0, doubleEOL, eolLength, eolLength); int separatorPos = StreamHelpers.FindIndex(buf, 0, length, doubleEOL); if (separatorPos == StreamHelpers.NOT_FOUND_POS) { throw new NFXException(StringConsts.MULTIPART_DOUBLE_EOL_ISNT_FOUND_AFTER_HEADER_ERROR + typeof(MultiPart).Name + ".Parse"); } string prmsStr = p.m_Encoding.GetString(buf, 0, separatorPos); p.m_Parameters = MultiPartParameters.Parse(prmsStr, p.m_EOL, p.m_Encoding); for (int iEOL = 0, iBuf = length - eolLength; iEOL < eolLength; iEOL++, iBuf++) { if (p.m_EOL[iEOL] != buf[iBuf]) { throw new NFXException("Invalid content EOL. " + typeof(MultiPart) + ".Parse()"); } } int contentLength = length - separatorPos - doubleEOLLength - eolLength; p.m_Content = new byte[contentLength]; Array.Copy(buf, separatorPos + doubleEOLLength, p.m_Content, 0, contentLength); if (p.Parameters.IsField) { p.m_ContentString = p.m_Encoding.GetString(p.m_Content); } return(p); }
private void parseStream(Stream stream, string boundary, Encoding encoding) { m_Stream = stream; string fullBoundary = new string(HYPHEN_CHAR, 2) + boundary; foreach (var segment in StreamHelpers.StreamSplitNew(stream, Encoding.UTF8.GetBytes(fullBoundary))) { var part = MultiPart.Parse(segment.Item1, segment.Item2); m_parts.Add(part); } }
public void TestAddFiles() { MultiPart mp = new MultiPart(); var name = "file"; var filename = "..\\..\\..\\espurl.explorer.tests\\testfile.txt"; mp.AddFileField(name, filename); string body = Helpers.ReadEntireStream(mp.GetStream()); string expected = string.Format("--{0}\r\n" + "Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n" + "{3}\r\n" + "--{0}--", mp.Boundary, name, filename, Helpers.ReadEntireStream(File.OpenRead(filename))); Assert.AreEqual(expected, body); }
private void SetInternaStructureForPart(IPart rootPart, string index) { this._partToIndex.Add(rootPart, index); this._indexToPart.Add(index, rootPart); if (rootPart.Type == EPartType.Content) { this.AddAttachment(rootPart); } if (rootPart.Type == EPartType.Multi) { MultiPart part = (MultiPart)rootPart; for (int i = 0; i < part.Parts.Count; i++) { this.SetInternaStructureForPart(part.Parts[i], string.Format("{0}.{1}", index, i + 1)); } } }
public void InitializeInternalStructure() { this._partToIndex.Clear(); this._indexToPart.Clear(); this._attachmentToPart.Clear(); if (this.RootPart.Type != EPartType.Multi) { this.SetInternaStructureForPart(this.RootPart, "1"); } else { MultiPart rootPart = (MultiPart)this.RootPart; for (int i = 0; i < rootPart.Parts.Count; i++) { this.SetInternaStructureForPart(rootPart.Parts[i], (i + 1).ToString()); } } }
public MultiPart ParseMultipart(byte[] source, string attachmentDirectory) { MultiPart part = new MultiPart(); List <byte[]> list = Skycap.Net.Imap.Parsers.Utils.ExtractParams(source); for (int i = 0; i < (list.Count - 1); i++) { part.Parts.Add(this.Parse(list[i], attachmentDirectory)); } Match match = new Regex("\\([\\s\\S]*\\) \"([^\"]+)\"").Match(Encoding.UTF8.GetString(source, 0, source.Length)); if (!match.Success) { throw new FormatException("The source string was not in a correct format"); } part.Header.ContentType = new ContentType("multipart", match.Groups[1].Value.ToLower()); return(part); }
public virtual MultiPart Parse(IMessageReader reader, EContentTransferEncoding contentTransferEncoding, string boundary, string uid, string attachmentDirectory, PopMessage parentMessage, ContentType contentType) { byte[] buffer; MultiPart part = new MultiPart(); string str2 = contentType.Attributes["boundary"]; this._childrenReachedFinalBoundary = false; do { buffer = reader.ReadLine(); }while (buffer != null && this._defaultEncoding.GetString(buffer, 0, buffer.Length) != ("--" + str2)); do { string source = Utils.ReadHeaders(reader); MIMEHeader header = new MIMEHeaderParser().Parse(source); if (reader.EndOfMessage) { break; } IPart part2 = this.ParsePart(reader, header.ContentID, header.ContentType, header.ContentDisposition, header.ContentTransferEncoding, uid, attachmentDirectory, str2, parentMessage); part2.Header = header; part2.Header.ContentTransferEncoding = header.IsDefaultContentTransferEncoding ? contentTransferEncoding : header.ContentTransferEncoding; part.Parts.Add(part2); }while (!this._childrenReachedFinalBoundary); while (!reader.EndOfMessage) { buffer = reader.ReadLine(); if (buffer == null) { this.RaiseFinalBoundaryReached(); return(part); } EBoundaryType type = BoundaryChecker.CheckBoundary(buffer, boundary); if (type != EBoundaryType.NotBoundary) { if (type == EBoundaryType.Final) { this.RaiseFinalBoundaryReached(); } return(part); } } return(part); }
public void TestAddFields() { MultiPart mp = new MultiPart(); var field1Name = "field1"; var field1Val = "a simple value"; var field2Name = "field2"; var field2Val = "another simple value"; mp.AddField(field1Name, field1Val); mp.AddField(field2Name, field2Val); string body = Helpers.ReadEntireStream(mp.GetStream()); string expected = string.Format("--{0}\r\n" + "Content-Disposition: form-data; name=\"{1}\"\r\n" + "Content-Type: text/plain; charset=utf-8\r\n\r\n" + "{2}\r\n" + "--{0}\r\n" + "Content-Disposition: form-data; name=\"{3}\"\r\n" + "Content-Type: text/plain; charset=utf-8\r\n\r\n" + "{4}\r\n" + "--{0}--", mp.Boundary, field1Name, field1Val, field2Name, field2Val); Assert.AreEqual(expected, body); }
private string GetPlainText(IPart node) { if (node.Type == EPartType.Multi) { MultiPart part = (MultiPart)node; if ((part.Header.ContentType.SubType.Equals("mixed", StringComparison.OrdinalIgnoreCase) || part.Header.ContentType.SubType.Equals("alternative", StringComparison.OrdinalIgnoreCase)) || part.Header.ContentType.SubType.Equals("related", StringComparison.OrdinalIgnoreCase)) { foreach (IPart part2 in ((MultiPart)node).Parts) { string plainText = this.GetPlainText(part2); if (plainText != null) { return(plainText); } } } } else if (PartUtils.IsTextPart(node.Header.ContentType, node.Header.ContentDisposition) && node.Header.ContentType.SubType.Equals("plain", StringComparison.CurrentCultureIgnoreCase)) { return(((TextPart)node).Text); } return(null); }
public void MergeFrom(Quest other) { if (other == null) { return; } if (other.QuestType != 0) { QuestType = other.QuestType; } if (other.dailyQuest_ != null) { if (dailyQuest_ == null) { dailyQuest_ = new global::POGOProtos.Data.Quests.DailyQuest(); } DailyQuest.MergeFrom(other.DailyQuest); } if (other.multiPart_ != null) { if (multiPart_ == null) { multiPart_ = new global::POGOProtos.Data.Quests.Quest.Types.MultiPartQuest(); } MultiPart.MergeFrom(other.MultiPart); } if (other.catchPokemon_ != null) { if (catchPokemon_ == null) { catchPokemon_ = new global::POGOProtos.Data.Quests.CatchPokemonQuest(); } CatchPokemon.MergeFrom(other.CatchPokemon); } if (other.addFriend_ != null) { if (addFriend_ == null) { addFriend_ = new global::POGOProtos.Data.Quests.AddFriendQuest(); } AddFriend.MergeFrom(other.AddFriend); } if (other.tradePokemon_ != null) { if (tradePokemon_ == null) { tradePokemon_ = new global::POGOProtos.Data.Quests.TradePokemonQuest(); } TradePokemon.MergeFrom(other.TradePokemon); } if (other.QuestId.Length != 0) { QuestId = other.QuestId; } if (other.QuestSeed != 0L) { QuestSeed = other.QuestSeed; } if (other.QuestContext != 0) { QuestContext = other.QuestContext; } if (other.TemplateId.Length != 0) { TemplateId = other.TemplateId; } if (other.Progress != 0) { Progress = other.Progress; } if (other.goal_ != null) { if (goal_ == null) { goal_ = new global::POGOProtos.Data.Quests.QuestGoal(); } Goal.MergeFrom(other.Goal); } if (other.Status != 0) { Status = other.Status; } questRewards_.Add(other.questRewards_); if (other.CreationTimestampMs != 0L) { CreationTimestampMs = other.CreationTimestampMs; } if (other.LastUpdateTimestampMs != 0L) { LastUpdateTimestampMs = other.LastUpdateTimestampMs; } if (other.CompeletionTimestampMs != 0L) { CompeletionTimestampMs = other.CompeletionTimestampMs; } if (other.FortId.Length != 0) { FortId = other.FortId; } if (other.AdminGenerated != false) { AdminGenerated = other.AdminGenerated; } if (other.StampCountOverrideEnabled != false) { StampCountOverrideEnabled = other.StampCountOverrideEnabled; } if (other.StampCountOverride != 0) { StampCountOverride = other.StampCountOverride; } if (other.S2CellId != 0L) { S2CellId = other.S2CellId; } if (other.StoryQuestTemplateVersion != 0) { StoryQuestTemplateVersion = other.StoryQuestTemplateVersion; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); }
public override int GetHashCode() { int hash = 1; if (QuestType != 0) { hash ^= QuestType.GetHashCode(); } if (dailyQuest_ != null) { hash ^= DailyQuest.GetHashCode(); } if (multiPart_ != null) { hash ^= MultiPart.GetHashCode(); } if (catchPokemon_ != null) { hash ^= CatchPokemon.GetHashCode(); } if (addFriend_ != null) { hash ^= AddFriend.GetHashCode(); } if (tradePokemon_ != null) { hash ^= TradePokemon.GetHashCode(); } if (QuestId.Length != 0) { hash ^= QuestId.GetHashCode(); } if (QuestSeed != 0L) { hash ^= QuestSeed.GetHashCode(); } if (QuestContext != 0) { hash ^= QuestContext.GetHashCode(); } if (TemplateId.Length != 0) { hash ^= TemplateId.GetHashCode(); } if (Progress != 0) { hash ^= Progress.GetHashCode(); } if (goal_ != null) { hash ^= Goal.GetHashCode(); } if (Status != 0) { hash ^= Status.GetHashCode(); } hash ^= questRewards_.GetHashCode(); if (CreationTimestampMs != 0L) { hash ^= CreationTimestampMs.GetHashCode(); } if (LastUpdateTimestampMs != 0L) { hash ^= LastUpdateTimestampMs.GetHashCode(); } if (CompeletionTimestampMs != 0L) { hash ^= CompeletionTimestampMs.GetHashCode(); } if (FortId.Length != 0) { hash ^= FortId.GetHashCode(); } if (AdminGenerated != false) { hash ^= AdminGenerated.GetHashCode(); } if (StampCountOverrideEnabled != false) { hash ^= StampCountOverrideEnabled.GetHashCode(); } if (StampCountOverride != 0) { hash ^= StampCountOverride.GetHashCode(); } if (S2CellId != 0L) { hash ^= S2CellId.GetHashCode(); } if (StoryQuestTemplateVersion != 0) { hash ^= StoryQuestTemplateVersion.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
private void parseStream() { m_Stream.Position = 0; long firstEOLPos = StreamHelpers.Find(m_Stream, EOL_CRLF_BYTES); if (firstEOLPos == StreamHelpers.NOT_FOUND_POS) { firstEOLPos = StreamHelpers.Find(m_Stream, EOL_LF_BYTES); if (firstEOLPos == StreamHelpers.NOT_FOUND_POS) { throw new NFXException(StringConsts.MULTIPART_NO_LF_NOR_CRLF_ISNT_FOUND_ERROR + this.GetType().Name + ".ParseStream"); } m_EOL = EOL_LF_BYTES; } else { m_EOL = EOL_CRLF_BYTES; } byte[] boundaryBytes = new byte[firstEOLPos]; boundaryBytes = new byte[firstEOLPos]; m_Stream.Read(boundaryBytes, 0, (int)firstEOLPos); if (m_Boundary != null) { string streamBoundaryStr = m_Encoding.GetString(boundaryBytes).Substring(2); if (streamBoundaryStr != m_Boundary) { throw new NFXException(StringConsts.MULTIPART_BOUNDARY_MISMATCH_ERROR.Args(m_Boundary, streamBoundaryStr) + this.GetType().Name + ".ParseStream"); } } else { var fullBoundary = m_Encoding.GetString(boundaryBytes); if (fullBoundary.Length < 3) { throw new NFXException(StringConsts.MULTIPART_BOUNDARY_COULDNT_BE_SHORTER_3_ERROR + this.GetType().Name + ".ParseStream"); } m_Boundary = fullBoundary.Substring(2); // remove two leading hyphens } m_Stream.Position = 0; int boundaryLength = boundaryBytes.Length; byte[] endBoundaryBytes = new byte[boundaryLength + 2]; m_Stream.Read(endBoundaryBytes, 0, boundaryLength); endBoundaryBytes[boundaryLength] = HYPHEN_BYTE; endBoundaryBytes[boundaryLength + 1] = HYPHEN_BYTE; long terminatorPos = StreamHelpers.Find(m_Stream, endBoundaryBytes); if (terminatorPos == StreamHelpers.NOT_FOUND_POS) { throw new NFXException(StringConsts.MULTIPART_TERMINATOR_ISNT_FOUND_ERROR + this.GetType().Name + ".ParseStream"); } var splitSegmentCoordinates = StreamHelpers.Split(m_Stream, boundaryBytes, whatLast: terminatorPos).ToArray(); foreach (var coordinate in splitSegmentCoordinates.Where(c => (c.Item2 - c.Item1) > m_EOL.Length)) { if (!StreamHelpers.EndsWith(m_Stream, m_EOL, coordinate.Item1, coordinate.Item2)) { throw new NFXException(StringConsts.MULTIPART_PART_SEGMENT_ISNT_TERMINATED_CORRECTLY_ERROR.Args(m_EOL) + this.GetType().Name + ".ParseStream"); } var part = new MultiPart(m_Stream, coordinate.Item1, coordinate.Item2 - m_EOL.Length, m_EOL, m_Encoding); m_Parts.Add(part); } }
public static MultiPart CreateField(string fieldName, string fieldValue, byte[] eol, Encoding encoding = null) { var parameters = MultiPartParameters.CreateField(fieldName, eol); var part = new MultiPart(parameters, eol, encoding); part.m_Content = (encoding ?? Encoding.UTF8).GetBytes(fieldValue); part.m_ContentString = fieldValue; return part; }
public static MultiPart CreateFile(string name, string fieldName, string contentType, byte[] content, byte[] eol, Encoding encoding = null) { var parameters = MultiPartParameters.CreateFile(name, fieldName, contentType, eol); var part = new MultiPart(parameters, eol, encoding); part.m_Content = content; return part; }
public static MultiPart Parse(byte[] buf, int length, Encoding encoding = null) { var p = new MultiPart(); if (buf[0] == MultiPartContent.LF) p.m_EOL = MultiPartContent.EOL_LF_BYTES; else if (buf[0] == MultiPartContent.CR && buf[1] == MultiPartContent.LF) p.m_EOL = MultiPartContent.EOL_CRLF_BYTES; else throw new NFXException(StringConsts.MULTIPART_NO_LF_NOR_CRLF_ISNT_FOUND_ERROR + typeof(MultiPart).Name + ".Parse"); int eolLength = p.m_EOL.Length; int doubleEOLLength = eolLength << 1; byte[] doubleEOL = new byte[doubleEOLLength]; Array.Copy(p.m_EOL, 0, doubleEOL, 0, eolLength); Array.Copy(p.m_EOL, 0, doubleEOL, eolLength, eolLength); int separatorPos = StreamHelpers.FindIndex(buf, 0, length, doubleEOL); if (separatorPos == StreamHelpers.NOT_FOUND_POS) throw new NFXException(StringConsts.MULTIPART_DOUBLE_EOL_ISNT_FOUND_AFTER_HEADER_ERROR + typeof(MultiPart).Name + ".Parse"); string prmsStr = (encoding ?? Encoding.UTF8).GetString(buf, 0, separatorPos); p.m_Parameters = MultiPartParameters.Parse(prmsStr, p.m_EOL); for (int iEOL = 0, iBuf = length - eolLength; iEOL < eolLength; iEOL++, iBuf++) if (p.m_EOL[iEOL] != buf[iBuf]) throw new NFXException("Invalid content EOL. " + typeof(MultiPart) + ".Parse()"); int contentLength = length - separatorPos - doubleEOLLength - eolLength; p.m_Content = new byte[contentLength]; Array.Copy(buf, separatorPos + doubleEOLLength, p.m_Content, 0, contentLength); if (p.Parameters.IsField) p.m_ContentString = (encoding ?? Encoding.UTF8).GetString(p.m_Content); return p; }
private void parseStream(Stream stream, Encoding encoding) { stream.Position = 0; long firstEOLPos = StreamHelpers.Find(stream, EOL_CRLF_BYTES); if (firstEOLPos == StreamHelpers.NOT_FOUND_POS) { firstEOLPos = StreamHelpers.Find(stream, EOL_LF_BYTES); if (firstEOLPos == StreamHelpers.NOT_FOUND_POS) throw new NFXException(StringConsts.MULTIPART_NO_LF_NOR_CRLF_ISNT_FOUND_ERROR + this.GetType().Name + ".ParseStream"); m_EOL = EOL_LF_BYTES; } else { m_EOL = EOL_CRLF_BYTES; } byte[] boundaryBytes = new byte[firstEOLPos]; boundaryBytes = new byte[firstEOLPos]; stream.Read(boundaryBytes, 0, (int)firstEOLPos); if (m_Boundary != null) { string streamBoundaryStr = Encoding.UTF8.GetString(boundaryBytes).Substring(2); if (streamBoundaryStr != m_Boundary) throw new NFXException(StringConsts.MULTIPART_BOUNDARY_MISMATCH_ERROR.Args(m_Boundary, streamBoundaryStr) + this.GetType().Name + ".ParseStream"); } else { var fullBoundary = Encoding.UTF8.GetString(boundaryBytes); if (fullBoundary.Length < 3) throw new NFXException(StringConsts.MULTIPART_BOUNDARY_COULDNT_BE_SHORTER_3_ERROR + this.GetType().Name + ".ParseStream"); m_Boundary = fullBoundary.Substring(2); // remove two leading hyphens } stream.Position = 0; int boundaryLength = boundaryBytes.Length; byte[] endBoundaryBytes = new byte[boundaryLength+2]; stream.Read(endBoundaryBytes, 0, boundaryLength); endBoundaryBytes[boundaryLength] = HYPHEN_BYTE; endBoundaryBytes[boundaryLength+1] = HYPHEN_BYTE; long terminatorPos = StreamHelpers.Find(stream, endBoundaryBytes); if (terminatorPos == StreamHelpers.NOT_FOUND_POS) throw new NFXException(StringConsts.MULTIPART_TERMINATOR_ISNT_FOUND_ERROR + this.GetType().Name + ".ParseStream"); var splitSegmentCoordinates = StreamHelpers.Split(stream, boundaryBytes, whatLast: terminatorPos).ToArray(); foreach (var coordinate in splitSegmentCoordinates.Where(c => (c.Item2 - c.Item1) > m_EOL.Length)) { if (!StreamHelpers.EndsWith(stream, m_EOL, coordinate.Item1, coordinate.Item2)) throw new NFXException(StringConsts.MULTIPART_PART_SEGMENT_ISNT_TERMINATED_CORRECTLY_ERROR.Args(m_EOL) + this.GetType().Name + ".ParseStream"); var part = new MultiPart( stream, coordinate.Item1, coordinate.Item2 - m_EOL.Length, m_EOL, (encoding ?? Encoding.UTF8)); Parts.Add(part); } }
/// <summary> /// Reads and parses the next response part. /// </summary> private async Task <MultiPart> ReadNextPartAsync() { var multiPart = new MultiPart(); // Response headers. while (CheckValidReadStates(await ReadNextLineAsync(), true, DataOrEmptyStates) == MultiPartReadState.Data) { if (!TryParseHeader(_line, out KeyValuePair <string, string[]> header)) { throw new InvalidOperationException("The multipart response header is malformed."); } multiPart.ResponseHeaders.Add(header.Key, header.Value); } // Check headers to determine if multipart changeset. if (multiPart.ResponseHeaders.ContainsKey("Content-Type")) { var val = multiPart.ResponseHeaders["Content-Type"]; if (val.Length > 0 && val[0] == "multipart/mixed") { var isInvalidMultiPart = true; if (val.Length > 1) { var nvp = SplitNameValuePair(val[1]); if (nvp.Item1 == "boundary" && nvp.Item2.StartsWith("changesetresponse_")) { isInvalidMultiPart = false; } } if (isInvalidMultiPart) { throw new InvalidOperationException("The multipart response has a Content-Type of multipart/mixed with an unexpected boundary."); } await ReadNextLineAsync(true); return(multiPart); } } // Response status. CheckValidReadStates(await ReadNextLineAsync(), true, MultiPartReadState.Data); if (!TryParseStatusCode(_line, out HttpStatusCode statusCode)) { throw new InvalidOperationException("Unexpected HTTP status code; response is malformed."); } multiPart.StatusCode = statusCode; // Content headers. while (CheckValidReadStates(await ReadNextLineAsync(), true, DataOrEmptyStates) == MultiPartReadState.Data) { if (!TryParseHeader(_line, out KeyValuePair <string, string[]> header)) { throw new InvalidOperationException("The multipart response header is malformed."); } multiPart.ContentHeaders.Add(header.Key, header.Value); } // Content. while (CheckValidReadStates(await ReadNextLineAsync(), false, MultiPartReadState.EndOfStream) == MultiPartReadState.Data) { multiPart.Content.AppendLine(_line); } // Move to non-empty state. if (_state == MultiPartReadState.Empty) { await ReadNextLineAsync(true); } multiPart.IsResponseMessage = true; return(multiPart); }
/// <summary> /// 发送请求 /// </summary> public void DoService() { if (string.IsNullOrEmpty(this.apiKey)) { this.haveDoneService = true; this.ocrResult = "Error:ApiKey 不能为空 "; return; } this.formData["apiKey"] = this.apiKey; this.formData["service"] = this.service.ToString(); this.formData["language"] = this.Language.ToString().ToLower(); if (this.language == Language.Eng) { this.formData["charset"] = ((int)this.charset).ToString(CultureInfo.InvariantCulture); } if (string.IsNullOrEmpty(this.filePath) && string.IsNullOrEmpty(this.fileUrl)) { this.haveDoneService = true; this.ocrResult = "Error:filePath 和 fileUrl 不能同时为空 "; return; } if (!string.IsNullOrEmpty(this.filePath) && File.Exists(this.filePath)) { if (string.IsNullOrEmpty(this.type)) { this.haveDoneService = true; this.ocrResult = "Error:上传识别验证码时 type 必须传图片的原始url "; return; } if (!this.type.StartsWith("http") && !this.type.StartsWith("ftp")) { this.haveDoneService = true; this.ocrResult = "Error:type 必须以 http/https/ftp 开头 "; return; } this.formData["type"] = this.type; this.response = MultiPart.MultiPost(this.apiUrl, this.formData, this.filePath); } else { if (string.IsNullOrEmpty(this.fileUrl)) { this.haveDoneService = true; this.ocrResult = "Error:filePath 和 fileUrl 不能同时为空 "; return; } this.formData["url"] = this.fileUrl; this.response = MultiPart.MultiPost(this.apiUrl, this.formData); } // 检查服务器响应状态 if (this.response.OK) { this.processStatus = true; this.ocrResult = this.response.Response; } else { this.ocrResult = string.Format("Error: {0}", this.response.StatusCode); } this.haveDoneService = true; }