Beispiel #1
0
 /// <summary>
 /// 生成微信AccessToken
 /// </summary>
 /// <param name="appId">ID</param>
 /// <param name="appSecret">秘钥</param>
 /// <param name="errMsg">出错信息</param>
 /// <returns></returns>
 public static string BuildAccessToken(string appId, string appSecret, out string errMsg)
 {
     errMsg = "";
     try
     {
         string    url       = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret);
         IHttpForm _httpForm = new HttpForm("", 15000, true, 8);
         url += "&rnd=" + Guid.NewGuid().ToString();
         HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest()
         {
             Url = url
         });
         Dictionary <object, object> dict = JsonConvert.DeserializeObject <Dictionary <object, object> >(_response.Response);
         if (dict.ContainsKey("access_token"))
         {
             return(dict["access_token"].ToString());
         }
         errMsg = string.Format("获取AccessToken失败:{0}", _response.Response);
         return("");
     }
     catch (Exception ex)
     {
         errMsg = string.Format("BuildAccessToken异常:{0}|{1}", ex.Message, ex.StackTrace);
         return("");
     }
 }
Beispiel #2
0
    /// <summary>
    /// Requests a synchronized http request to a determinated host and send the data in $_POST
    /// </summary>
    public void SyncRequest()
    {
        var request = new HttpRequest();
        var form    = new HttpForm();

        form.AddField("username", userField.text);
        form.AddField("password", pwdField.text);
        form.AddField("token", db.Token);
        request.Post(db.HttpLinks[0], form);

        Debug.Log("Request Headers : " + request.headers);
        Debug.Log("Request post data :" + form.ToString());

        if (request.isDone)
        {
            if (!request.isError || request.statusCode == System.Net.HttpStatusCode.OK)
            {
                ResponseTarget.text = "Success Response: " + request.ContentResponse;
                Debug.Log(request.ContentResponse);
            }
            else
            {
                ResponseTarget.text  = "Response: " + request.statusCode;
                ResponseTarget.color = Color.red;
                Debug.Log("status code error : " + request.statusCode);
            }
        }
    }
Beispiel #3
0
        /// <summary>
        /// 获取access_token,获取授权,返回json数据
        /// </summary>
        private string GetGrantTypeRequest(string appid, string appsecret, int flag)
        {
            string url = string.Empty;

            if (flag == 2)
            {
                url = string.Format("https://api.yixin.im/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);
            }
            else if (flag == 1)
            {
                url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);
            }
            else if (flag == 3)
            {
                return("");
            }
            IHttpForm        _httpForm = new HttpForm(managerSiteAddr, 1500, true, 8);
            HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest()
            {
                Url = url
            });
            string json = _response.Response.ToString();

            return(json);
        }
        private void ReportButtonClick(object sender, RoutedEventArgs e)
        {
            var userSettings = UnityInstance.Container.Resolve <IUserSettingsProvider>();
            var formData     = new List <IFormData>
            {
                new ErrorReport
                {
                    Name                   = "log",
                    ClientId               = userSettings.ClientId.ToString(),
                    ApplicationVersion     = App.ApplicationVersion,
                    FrameworkVersion       = App.FrameworkVersion,
                    OperatingSystemVersion = Environment.OSVersion.VersionString,
                    Details                = _details,
                    FtpLog                 = GetFtpLog()
                }
            };
            var iw = 0;

            foreach (Window window in Application.Current.Windows)
            {
                formData.Add(new WindowScreenshotReport
                {
                    Name   = "window" + iw,
                    Window = window
                });
                iw++;
            }

            HttpForm.Post("report.php", formData);
            OkButtonClick(sender, e);
        }
Beispiel #5
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="stream">Stream containing the content</param>
    /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
    /// <param name="encoding">Stream encoding</param>
    /// Note: contentType and encoding are not used?
    /// <returns>A http form, or null if content could not be parsed.</returns>
    /// <exception cref="InvalidDataException"></exception>
    public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
    {
      if (stream == null || stream.Length == 0)
        return null;
      if (!CanParse(contentType))
        return null;
      if (encoding == null)
        encoding = Encoding.UTF8;

      HttpForm form = new HttpForm();

      using (TextReader reader = new StreamReader(stream, encoding))
      {
        // let's start with saving the raw xml
        form.Add("__xml__", reader.ReadToEnd());

        try
        {
          // Now let's process the data.
          XmlDocument doc = new XmlDocument();
          doc.LoadXml(form["__xml__"].Value);
          XmlNode child = doc.FirstChild;
          // Skip to next node if the node is an XML Declaration 
          if (child.NodeType == XmlNodeType.XmlDeclaration)
            child = child.NextSibling;
          TraverseNode(form, child);
        }
        catch (XmlException err)
        {
          throw new InvalidDataException("Failed to traverse XML", err);
        }
      }

      return form;
    }
        protected HttpForm DecodePost(Hashtable request)
        {
//            Hashtable form = (Hashtable)request["form"];
//            m_log.InfoFormat("[WATER WARS]: Got {0} items in form", form.Count);
//            foreach (object key in form)
//            {
//                DictionaryEntry tuple = (DictionaryEntry)key;
//                m_log.InfoFormat("[WATER WARS]: Form tuple {0}={1}", tuple.Key, tuple.Value);
//            }

            IFormDecoder formDecoder = new MultipartDecoder();
            HttpForm     form2
                = formDecoder.Decode(
                      new MemoryStream(Encoding.UTF8.GetBytes((string)request["body"])),
                      (string)request["content-type"],
                      Encoding.UTF8);

//            m_log.InfoFormat("[WATER WARS]: Got {0} items in form2", form2.Count);
//            foreach (object key in form2)
//            {
//                DictionaryEntry tuple = (DictionaryEntry)key;
//                m_log.InfoFormat("[WATER WARS]: Form2 tuple {0}={1}", tuple.Key, tuple.Value);
//            }

//            foreach (HttpInputItem item in form2)
//            {
//                m_log.InfoFormat("[WATER WARS]: Got form item {0}={1}", item.Name, item.Value);
//            }

            return(form2);
        }
Beispiel #7
0
 /// <summary>
 /// 生成JSSDK_API调用用到的票据
 /// </summary>
 /// <param name="accessToken"></param>
 /// <param name="errMsg">出错信息</param>
 /// <returns></returns>
 public static string BuildJsApiTickets(string accessToken, out string errMsg)
 {
     errMsg = "";
     try
     {
         string    url       = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={0}", accessToken);
         IHttpForm _httpForm = new HttpForm("", 1500, true, 8);
         url += "&rnd=" + Guid.NewGuid().ToString();
         HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest()
         {
             Url = url
         });
         Dictionary <object, object> dict = JsonConvert.DeserializeObject <Dictionary <object, object> >(_response.Response);
         if (dict.ContainsKey("ticket"))
         {
             return(dict["ticket"].ToString());
         }
         errMsg = string.Format("获取JsApiTickets失败:{0}", _response.Response);
         return("");
     }
     catch (Exception ex)
     {
         errMsg = string.Format("BuildJsApiTickets异常::{0}|{1}", ex.Message, ex.StackTrace);
         return("");
     }
 }
        protected JObject GetJsonFromPost(Hashtable request)
        {
            HttpForm form    = DecodePost(request);
            string   rawJson = (string)form["json"].Value;

            // FIXME: Nasty way of unescaping the \"
            rawJson = rawJson.Replace(@"\", "");
            return(JObject.Parse(rawJson));
        }
Beispiel #9
0
    /// <summary>
    /// Request a pure HttpRequest synchronized which do not return but his data may be accessed on the created instance
    /// </summary>
    /// <param name="url"></param>
    /// <param name="data"></param>
    public void Post(string url, HttpForm data)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method      = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data.ToString());
            request.ContentLength = bytes.Length;

            Stream os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();

            if (resp == null)
            {
                ContentResponse = String.Empty;
            }

            StreamReader sr = new StreamReader(resp.GetResponseStream());

            //Releases the resources of the response
            resp.Close();

            //The request was successfull
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                //Set instance data
                ContentResponse = sr.ReadToEnd().Trim();
                headers         = resp.Headers.ToString();
                length          = resp.ContentLength;
                this.url        = url;
                this.bytes      = bytes;
                isJson          = JsonHelper.isJson(ContentResponse);
                statusCode      = resp.StatusCode;
                isError         = false;
            }
        }
        catch (WebException e)
        {
            Debug.Log("\r Web Exception :  " + e.Status);
            isError = true;
        }
        catch (Exception e)
        {
            Debug.Log("\r The following exception was raised : " + e.Message);
            isError = true;
        }
        finally
        {
            isDone = true;
        }
    }
Beispiel #10
0
        /// <summary>
        /// 自定义菜单get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="access_token"></param>
        /// <returns></returns>
        private string MenuRequest(string url, string access_token)
        {
            IHttpForm        _httpForm = new HttpForm(managerSiteAddr, 1500, true, 8);
            HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest()
            {
                Url = url
            });
            string json = _response.Response.ToString();

            return(json);
        }
Beispiel #11
0
        public static void SendMultipart(HttpForm aForm, HttpWebRequest aRequest)
        {
            // string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            aRequest.ServicePoint.Expect100Continue = false;

            string boundary = Guid.NewGuid().ToString();


            aRequest.ContentType = $"multipart/form-data; boundary={boundary}";
            aRequest.Method      = "POST";
            //  aRequest.KeepAlive = true;

            Stream memStream = new System.IO.MemoryStream();

            var    boundarybytes    = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            var    endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";


            foreach (HttpInputItem form in aForm)
            {
                string formitem      = string.Format(formdataTemplate, form.Name, form.Value);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            string headerTemplate =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                "Content-Type: {2}\r\n\r\n";

            foreach (HttpFile file in aForm.Files)
            {
                var path = RenameFile(file.Filename, file.UploadFilename);
                memStream.Write(boundarybytes, 0, boundarybytes.Length);                            // Boundary
                var header      = string.Format(headerTemplate, file.Name, path, file.ContentType); //Maybe  UploadFileName
                var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);

                byte[] fileBuffer = File.ReadAllBytes(path);
                memStream.Write(fileBuffer, 0, fileBuffer.Length);
            }

            memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            aRequest.ContentLength = memStream.Length;

            using (Stream requestStream = aRequest.GetRequestStream())
            {
                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            }
        }
Beispiel #12
0
        private static string DoPost(NameValueCollection collection)
        {
            IHttpForm        httpForm = new HttpForm("", 60000, true, 8);
            HttpFormResponse response = httpForm.Post(new HttpFormPostRequest()
            {
                Url        = Config.GATE_WAY,
                FormFields = collection
            });

            return(response.Response);
        }
        public void PrepareRequestBody_Should_Return_Correct_Body()
        {
            NameValueCollection formFields = new NameValueCollection
            {
                { "foo", "bar" },
                { "hello", "world" }
            };

            string body = HttpForm.PrepareRequestBody(formFields);

            Assert.Equal("foo=bar&hello=world", body);
        }
        private void TestPost()
        {
            MyController  controller = new MyController();
            IHttpResponse response;
            IHttpSession  session = DefaultSession;
            HttpForm      form    = new HttpForm();

            form.Add("user[firstName]", "jonas");
            string text = Post(controller, "/my/hello/id", form, out response, session);

            Assert.Equal("jonas", text);
        }
Beispiel #15
0
        public void ReadResponse_Should_Return_Correct_Response()
        {
            const string Response = "Test Response";

            Mock <WebRequest> request = MockRequest(Response);

            request.Setup(r => r.GetResponse()).Throws <WebException>();

            var result = HttpForm.ReadResponse(request.Object);

            Assert.Null(result.Response);
        }
        public void ReadResponse_Should_Return_Null_For_Invalid_Url()
        {
            const string Response = "Test Response";

            Mock <WebRequest> request = MockRequest(Response);

            request.Expect(r => r.GetResponse()).Throws <WebException>();

            var result = HttpForm.ReadResponse(request.Object);

            Assert.Null(result);
        }
Beispiel #17
0
        /// <summary>
        /// 设置自定义菜单(包含创建和删除)
        /// </summary>
        /// <param name="postData">菜单json数据</param>
        /// <param name="access_token">凭证</param>
        /// <returns></returns>
        private string CreateMenuRequest(string url, string postData, string access_token)
        {
            IHttpForm        _httpForm = new HttpForm(managerSiteAddr, 1500, true, 8);
            HttpFormResponse _response = _httpForm.Post(new HttpFormPostRawRequest()
            {
                Url  = url,
                Data = postData
            });
            string json = _response.Response.ToString();

            return(json);
        }
        public static Task <IllustsPage> GetIllustRankingAsync(this PixivClient client, RankMode mode = RankMode.Day, DateTime?date = default, int offset = 0)
        {
            var data = new HttpForm {
                { "offset", offset.ToString() }, { "mode", mode.GetSymbol() }
            };

            if (date != null)
            {
                data.Add("date", date.Value.ToString("yyyy-MM-dd"));
            }

            return(client.GetAsync <IllustsPage>("/v1/illust/ranking", data));
        }
        public static Task <IllustsPage> SearchIllustAsync(this PixivClient client, string word, SearchMode mode = SearchMode.PartialMatchTags, SortOptions sortOptions = SortOptions.DateDecreasing, SearchDuration?duration = default, int offset = 0)
        {
            var data = new HttpForm {
                { "word", word }, { "search_target", mode.GetSymbol() }, { "sort", sortOptions.GetSymbol() }, { "offset", offset.ToString() }
            };

            if (duration != null)
            {
                data.Add("duration", duration.GetSymbol());
            }

            return(client.GetAsync <IllustsPage>("/v1/search/illust"));
        }
Beispiel #20
0
        public String[] test(String filename)
        {
            var file1 = filename;

            var yourUrl  = "http://scan4you.net/remote.php";
            var httpForm = new HttpForm(yourUrl);

            httpForm.AttachFile("file1", file1);
            httpForm.SetValue("id", "34681").SetValue("token", "fe8f7ffa233eb2e6f189");
            HttpWebResponse response = httpForm.Submit();

            return(parseResponse(response));
        }
        private static void RetryFailedUserReports()
        {
            var queue = Directory.GetDirectories(App.PostDirectory);

            foreach (var item in queue.OrderBy(f => f))
            {
                var file = Directory.GetFiles(item).First();
                if (!HttpForm.Repost(file))
                {
                    continue;
                }
                Directory.Delete(item, true);
            }
        }
        public bool TryExport(string deviceId, string userName)
        {
            try {
                System.Net.ServicePointManager.DnsRefreshTimeout = 0;
                var client = new HttpForm(AppSettings.ApiEndpoint);
                client.AttachFile(userName, _filesystem.Combine($"{AccountFolder}/{userName}.json"));
                client.AttachFile($"{userName}_data", _filesystem.Combine($"{AccountDataFolder}/{userName}_data.json"));
                client.SetValue("deviceId", deviceId);

                var response = client.Submit();
                return(response.StatusCode == System.Net.HttpStatusCode.OK);
            } catch (Exception) {
                return(false);
            }
        }
        public void TestSimple()
        {
            UrlDecoder decoder = new UrlDecoder();

            using (MemoryStream stream = new MemoryStream())
            {
                byte[] bytes = Encoding.ASCII.GetBytes(@"not encoded or anything");
                stream.Write(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin);
                HttpForm form = decoder.Decode(stream,
                                               "application/x-www-form-urlencoded",
                                               Encoding.ASCII);
                Assert.Equal("not encoded or anything", form[string.Empty].Value);
            }
        }
Beispiel #24
0
        /// <summary> Test a correct decoding </summary>
        public void TestDecode()
        {
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(requestText));
            HttpForm     form   = _decoder.Decode(stream, "multipart/form-data; boundary=---------------------------18506757825014", Encoding.UTF8);

            Assert.True(form["HiddenField"].Contains("buttomAss"));
            Assert.True(form["HiddenField"].Contains("monkeyAss"));
            Assert.Equal("Hejsan", form["HiddenField"]["monkeyAss"].Value);
            Assert.Equal("Tjosan", form["HiddenField"]["buttomAss"].Value);
            Assert.NotNull(form.GetFile("VCardFile"));
            Assert.False(string.IsNullOrEmpty(form.GetFile("VCardFile").Filename));
            Assert.True(File.Exists(form.GetFile("VCardFile").Filename));
            form.GetFile("VCardFile").Dispose();

            stream.Dispose();
        }
Beispiel #25
0
        protected override void OkButtonClick(object sender, RoutedEventArgs e)
        {
            var p = No.IsChecked == true;

            if (UserSettings.DisableUserStatisticsParticipation != p)
            {
                _workHandler.Run(() => HttpForm.Post("clients.php", new List <IFormData>
                {
                    new RawPostData("client_id", UserSettings.ClientId),
                    new RawPostData("date", DateTime.Now.ToUnixTimestamp()),
                    new RawPostData("participates", p ? "yes" : "no"),
                }));
            }
            UserSettings.DisableUserStatisticsParticipation = p;
            base.OkButtonClick(sender, e);
        }
Beispiel #26
0
        public string BuildAccessToken(string appid, string appsecret, int customerId)
        {
            string           url       = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);
            IHttpForm        _httpForm = new HttpForm("", 15000, true, 8);
            HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest()
            {
                Url = url
            });
            Dictionary <object, object> dict = JsonConvert.DeserializeObject <Dictionary <object, object> >(_response.Response);

            if (dict.ContainsKey("access_token"))
            {
                return(dict["access_token"].ToString());
            }
            throw new Exception(string.Format("非Senparc获取AccessToken失败->appid:{0},appsecret:{1},商户Id:{2}", appid, appsecret, customerId));
        }
        public void ResponseCallback_WithException()
        {
            var request = new Mock <WebRequest>();

            var state = new HttpForm.StateContainer
            {
                Request    = request.Object,
                OnComplete = delegate { },
                OnError    = delegate { }
            };

            var result = new Mock <IAsyncResult>();

            result.ExpectGet(r => r.AsyncState).Returns(state);
            request.Expect(r => r.GetResponse()).Throws <WebException>();

            HttpForm.ResponseCallback(result.Object);
        }
Beispiel #28
0
        private static string GetPostData(HttpForm form)
        {
            StringBuilder post = new StringBuilder();

            foreach (HttpInputItem item in form)
            {
                post.AppendFormat("{0}={1}&", item.Name, item.Value);
            }

            string result = post.ToString();

            if (result.EndsWith("&"))
            {
                result = result.Substring(0, result.Length - 1);
            }

            return(result);
        }
Beispiel #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
        /// <param name="encoding">Stream encoding</param>
        /// Note: contentType and encoding are not used?
        /// <returns>A http form, or null if content could not be parsed.</returns>
        /// <exception cref="InvalidDataException"></exception>
        public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
        {
            if (stream == null || stream.Length == 0)
            {
                return(null);
            }
            if (!CanParse(contentType))
            {
                return(null);
            }
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            HttpForm form = new HttpForm();

            using (TextReader reader = new StreamReader(stream, encoding))
            {
                // let's start with saving the raw xml
                form.Add("__xml__", reader.ReadToEnd());

                try
                {
                    // Now let's process the data.
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(form["__xml__"].Value);
                    XmlNode child = doc.FirstChild;
                    // Skip to next node if the node is an XML Declaration
                    if (child.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        child = child.NextSibling;
                    }
                    TraverseNode(form, child);
                }
                catch (XmlException err)
                {
                    throw new InvalidDataException("Failed to traverse XML", err);
                }
            }

            return(form);
        }
Beispiel #30
0
 /// <summary>
 /// 获取微信用户基本信息(包括UnionID机制)
 /// </summary>
 /// <param name="accessToken"></param>
 /// <param name="openid"></param>
 /// <returns></returns>
 public static MPUserInfoResult GetWxUserInfo(string wxApiUrl, out string errmsg)
 {
     errmsg = "";
     try
     {
         IHttpForm        _httpForm = new HttpForm("HOT-MPHelper", 15000, true, 8);
         HttpFormResponse _response = _httpForm.Get(new HttpFormGetRequest()
         {
             Url = wxApiUrl
         });
         MPUserInfoResult result = JsonConvert.DeserializeObject <MPUserInfoResult>(_response.Response);
         return(result);
     }
     catch (Exception ex)
     {
         errmsg = ex.Message;
         LogHelper.Write("获取微信用户基本信息(GetWxUserInfo)异常 -->:" + ex.Message);
         return(null);
     }
 }
        public void WriteCallback_WithException()
        {
            var request = new Mock <WebRequest>();
            var stream  = new Mock <Stream>();

            var state = new HttpForm.StateContainer
            {
                Request        = request.Object,
                RequesteStream = stream.Object,
                OnComplete     = delegate { },
                OnError        = delegate { }
            };

            var result = new Mock <IAsyncResult>();

            result.ExpectGet(r => r.AsyncState).Returns(state);
            stream.Expect(s => s.EndWrite(It.IsAny <IAsyncResult>()));
            stream.Expect(s => s.Close());
            request.Expect(r => r.BeginGetResponse(It.IsAny <AsyncCallback>(), It.IsAny <HttpForm.StateContainer>())).Throws <WebException>();

            HttpForm.WriteCallback(result.Object);
        }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="stream">Stream containing the content</param>
    /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
    /// <param name="encoding">Stream enconding</param>
    /// <returns>A http form, or null if content could not be parsed.</returns>
    /// <exception cref="InvalidDataException">If contents in the stream is not valid input data.</exception>
    /// <exception cref="ArgumentNullException">If any parameter is null</exception>
    public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
    {
      if (stream == null)
        throw new ArgumentNullException("stream");
      if (string.IsNullOrEmpty(contentType))
        throw new ArgumentNullException("contentType");
      if (encoding == null)
        throw new ArgumentNullException("encoding");

      if (!CanParse(contentType))
        throw new InvalidOperationException("Cannot parse contentType: " + contentType);

      //multipart/form-data, boundary=AaB03x
      int pos = contentType.IndexOf("=");
      if (pos == -1)
        throw new InvalidDataException("Missing boundry in content type.");

      string boundry = contentType.Substring(pos + 1).Trim();
      HttpMultipart multipart = new HttpMultipart(stream, boundry, encoding);

      HttpForm form = new HttpForm();

      HttpMultipart.Element element;
      while ((element = multipart.ReadNextElement()) != null)
      {
        if (string.IsNullOrEmpty(element.Name))
          throw new InvalidDataException("Error parsing request. Missing value name.\nElement: " + element);

        if (!string.IsNullOrEmpty(element.Filename))
        {
          if (string.IsNullOrEmpty(element.ContentType))
            throw new InvalidDataException("Error parsing request. Value '" + element.Name + "' lacks a content type.");

          // Read the file data
          byte[] buffer = new byte[element.Length];
          stream.Seek(element.Start, SeekOrigin.Begin);
          stream.Read(buffer, 0, (int) element.Length);

          // Generate a filename
          string filename = element.Filename;
          string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
          // if the internet path doesn't exist, assume mono and /var/tmp
          string path = string.IsNullOrEmpty(internetCache)
              ? Path.Combine("var", "tmp")
              : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");
          element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

          // If the file exists generate a new filename
          while (File.Exists(element.Filename))
            element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");

          if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

          File.WriteAllBytes(element.Filename, buffer);
          form.AddFile(new HttpFile(element.Name, element.Filename, element.ContentType, filename));
        }
        else
        {
          byte[] buffer = new byte[element.Length];
          stream.Seek(element.Start, SeekOrigin.Begin);
          stream.Read(buffer, 0, (int) element.Length);
          form.Add(element.Name, encoding.GetString(buffer));
        }
      }

      return form;
    }
Beispiel #33
0
 /// <summary>
 /// Decode body into a form.
 /// </summary>
 /// <param name="providers">A list with form decoders.</param>
 /// <exception cref="InvalidDataException">If body contents is not valid for the chosen decoder.</exception>
 /// <exception cref="InvalidOperationException">If body is still being transferred.</exception>
 public void DecodeBody(FormDecoderProvider providers)
 {
     _form = providers.Decode(_headers["content-type"], _body, Encoding.UTF8);
 }
Beispiel #34
0
 public HttpTestRequest()
 {
     _queryString = new HttpInput("QueryString");
     _form = new HttpForm();
     _param = new HttpParam(_form, _queryString);
 }
Beispiel #35
0
 private void TestPost()
 {
     MyController controller = new MyController();
     IHttpResponse response;
     IHttpSession session = DefaultSession;
     HttpForm form = new HttpForm();
     form.Add("user[firstName]", "jonas");
     string text = Post(controller, "/my/hello/id", form, out response, session);
     Assert.Equal("jonas", text);
 }
Beispiel #36
0
 /// <summary>
 /// Send a POST request to a controller.
 /// </summary>
 /// <param name="controller">Controller receiving the post request.</param>
 /// <param name="uri">Uri visited.</param>
 /// <param name="form">Form being processed by controller.</param>
 /// <param name="response">Response from the controller.</param>
 /// <param name="session">Session used during the test. null = <see cref="DefaultSession"/> is used.</param>
 /// <returns>body posted by the response object</returns>
 /// <example>
 /// <code>
 /// void MyTest()
 /// {
 ///     // Create a controller.
 ///     MyController controller = new MyController();
 ///
 ///     // build up a form that is used by the controller.
 ///     HttpForm form = new HttpForm();
 ///     form.Add("user[firstName]", "Jonas");
 /// 
 ///     // Invoke the request
 ///     ControllerTester tester = new ControllerTester();
 ///     IHttpResponse response;
 ///     string text = tester.Get(controller, "/user/create/", form, out response, null);
 /// 
 ///     // validate response back from controller.
 ///     Assert.Equal("User 'Jonas' has been created.", text);
 /// }
 /// </code>
 /// </example>
 public string Post(RequestController controller, string uri, HttpForm form, out IHttpResponse response, IHttpSession session)
 {
     return Invoke(controller, Method.Post, uri, form, out response, session);
 }
Beispiel #37
0
        private static string GetPostData(HttpForm form)
        {
            StringBuilder post = new StringBuilder();

            foreach (HttpInputItem item in form)
            {
                post.AppendFormat("{0}={1}&", item.Name, item.Value);
            }

            string result = post.ToString();

            if (result.EndsWith("&"))
            {
                result = result.Substring(0, result.Length - 1);
            }

            return result;
        }
Beispiel #38
0
// ReSharper disable SuggestBaseTypeForParameter
    	/// <exception cref="NotFoundException"><c>NotFoundException</c>.</exception>
    	private string Invoke(RequestController controller, string httpMetod, string uri, HttpForm form, out IHttpResponse response, IHttpSession session)
// ReSharper restore SuggestBaseTypeForParameter
        {
            HttpRequest request = new HttpRequest
                                  	{
                                  		HttpVersion = "HTTP/1.1",
                                  		UriPath = uri,
                                  		Method = httpMetod,
                                  		Uri = new Uri(HostName + uri)
                                  	};
			response = request.CreateResponse(TestContext);
			/*
        	request.AssignForm(form);

            if(!controller.Process(request, response, session))
                throw new NotFoundException("404 could not find processor for: " + uri);
           
            response.Body.Seek(0, SeekOrigin.Begin);
            StreamReader reader = new StreamReader(response.Body);
            return reader.ReadToEnd();
			 * */
    		return null;
        }