void LoadContent(HttpWebRequest httpRequest, XPathHttpMultipart multipart) { string boundary = multipart.Boundary; if (String.IsNullOrEmpty(boundary)) boundary = "----------" + DateTime.Now.Ticks.ToString("x"); Encoding encoding = Encoding.UTF8; string newLine = Environment.NewLine; byte[] newLineBytes = encoding.GetBytes(newLine); List<byte[]> headers = new List<byte[]>(); byte[] footer = encoding.GetBytes(String.Concat("--", boundary, "--", newLine)); long contentLength = 0; for (int i = 0; i < multipart.Items.Count; i++) { var item = multipart.Items[i]; StringBuilder sb = new StringBuilder() .Append("--") .Append(boundary) .Append(newLine); foreach (string key in item.Headers) { sb.Append(key) .Append(": ") .Append(item.Headers[key]) .Append(newLine); } sb.Append(newLine); byte[] header = encoding.GetBytes(sb.ToString()); headers.Add(header); contentLength += header.LongLength; contentLength += item.Body.PrepareContent(this.ItemFactory, this.Resolver); contentLength += newLineBytes.LongLength; } contentLength += footer.LongLength; httpRequest.ContentLength = contentLength; httpRequest.ContentType = String.Concat(multipart.MediaType, "; boundary=", boundary); using (Stream requestStream = httpRequest.GetRequestStream()) { for (int i = 0; i < multipart.Items.Count; i++) { byte[] header = headers[i]; requestStream.Write(header, 0, header.Length); using (Stream contentStream = multipart.Items[i].Body.GetContentStream()) { contentStream.CopyTo(requestStream); requestStream.Write(newLineBytes, 0, newLineBytes.Length); } } requestStream.Write(footer, 0, footer.Length); } }
XPathHttpResponse GetResponse(HttpWebResponse httpResponse) { XPathHttpResponse response = new XPathHttpResponse { Status = httpResponse.StatusCode, Message = httpResponse.StatusDescription, Headers = { httpResponse.Headers } }; if (httpResponse.ContentLength > 0) { string mediaType = ""; try { ContentType contentType = new ContentType(httpResponse.ContentType); mediaType = contentType.MediaType; } catch (FormatException) { } catch (ArgumentException) { } if (MediaTypes.IsMultipart(mediaType)) { XPathHttpMultipart multipart = new XPathHttpMultipart { MediaType = mediaType }; using (Stream responseBody = httpResponse.GetResponseStream()) multipart.Deserialize(responseBody, this.StatusOnly); response.Multipart = multipart; } else { XPathHttpBody body = new XPathHttpBody { MediaType = mediaType }; if (!String.IsNullOrEmpty(httpResponse.CharacterSet)) { try { body.Encoding = Encoding.GetEncoding(httpResponse.CharacterSet); } catch (ArgumentException) { } } if (!this.StatusOnly) { using (Stream responseBody = httpResponse.GetResponseStream()) body.Deserialize(responseBody, httpResponse.ResponseUri, this.ItemFactory, this.OverrideMediaType); } response.Body = body; } } return response; }