Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Zelka.Apis
- {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- public class MultiformRequest
- {
- private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 OPR/20.0.1387.82";
- private readonly string Boundary;
- public MultiformRequest(string url)
- {
- this.Url = url;
- this.Boundary = GetNewBoundary();
- this.Stream = new MemoryStream();
- this.RequestParameters = new List<IRequestParameter>();
- this.Encoding = Encoding.UTF8;
- this.UserAgent = DefaultUserAgent;
- this.CookieContainer = new CookieContainer();
- }
- public string Url { get; set; }
- public Encoding Encoding { get; set; }
- private Stream Stream { get; set; }
- public string UserAgent { get; set; }
- public CookieContainer CookieContainer { get; set; }
- public List<IRequestParameter> RequestParameters { get; set; }
- public HttpWebResponse GetResponse()
- {
- this.AddRequestParameters();
- this.AddRequestFooter();
- byte[] requestData = this.GetDataFromStream();
- HttpWebRequest request = this.BuildRequest(requestData);
- return request.GetResponse() as HttpWebResponse;
- }
- private HttpWebRequest BuildRequest(byte[] requestData)
- {
- HttpWebRequest request = WebRequest.Create(this.Url) as HttpWebRequest;
- request.Method = "POST";
- request.ContentType = "multipart/form-data; boundary=" + this.Boundary;
- request.UserAgent = this.UserAgent;
- request.CookieContainer = this.CookieContainer;
- request.ContentLength = requestData.Length;
- WriteDataToStream(requestData, request.GetRequestStream());
- return request;
- }
- private static void WriteDataToStream(byte[] requestData, Stream stream)
- {
- stream.Write(requestData, 0, requestData.Length);
- stream.Close();
- }
- private byte[] GetDataFromStream()
- {
- this.Stream.Position = 0;
- byte[] formData = new byte[this.Stream.Length];
- this.Stream.Read(formData, 0, formData.Length);
- this.Stream.Close();
- return formData;
- }
- private void AddRequestParameters()
- {
- bool needsNewLine = false;
- foreach (IRequestParameter parameter in this.RequestParameters)
- {
- if (needsNewLine)
- {
- this.Stream.Write(this.Encoding.GetBytes("\r\n"), 0, this.Encoding.GetByteCount("\r\n"));
- }
- needsNewLine = true;
- parameter.WriteToStream(this.Stream, this.Boundary, this.Encoding);
- }
- }
- private void AddRequestFooter()
- {
- string footer = "\r\n--" + this.Boundary + "--\r\n";
- this.Stream.Write(this.Encoding.GetBytes(footer), 0, this.Encoding.GetByteCount(footer));
- }
- private static string GetNewBoundary()
- {
- return string.Format("----------{0:N}", Guid.NewGuid());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement