Example #1
0
        public static async ValueTask <string> Request(HttpMethod Method, string URI, string Parameters = null)
        //, string ProxyString
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            //req.Proxy = new System.Net.WebProxy(ProxyString, true);
            //Add these, as we're doing a POST
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method      = Method.Method;
            if (!string.IsNullOrEmpty(Parameters))
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(await req.GetRequestStreamAsync()))
                //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
                {
                    //req.ContentLength = sw.Encoding.GetBytes(Parameters).Length;
                    sw.Write(Parameters); //Push it out there
                    sw.Flush();
                }
            }
            System.Net.WebResponse resp = await req.GetResponseAsync();

            if (resp == null)
            {
                return(null);
            }
            using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                return(sr.ReadToEnd().Trim());
        }
Example #2
0
        internal async System.Threading.Tasks.Task <string> HttpPost(string URI, string Parameters)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(BaseURI + URI);
            req.ContentType = "application/json";
            req.Method      = "POST";
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            //req.ContentLength = bytes.Length;
            System.IO.Stream os = await req.GetRequestStreamAsync();

            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Dispose();
            System.Net.WebResponse resp = await req.GetResponseAsync();

            if (resp == null)
            {
                return(null);
            }
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            return(sr.ReadToEnd().Trim());
        }
Example #3
0
        protected override async Task FillDataTo(System.Net.WebRequest webrqst, CancellationToken cancellationToken, IProgress <ProgressReport> progress)
        {
            progress.ReportWhenNotNull(() => ProgressReport
                                       .CreateNew(RequestResponseSteps
                                                  .Requesting_N_Uploading, 0, 1));
            var qd = System.Text.Encoding.UTF8.GetBytes(JsonClientHelper.GetQueryData(RequestData.PostFieldValues));

            webrqst.ContentType = "application/x-www-form-urlencoded";
#if SILVERLIGHT_4 || SILVERLIGHT_5 || DOTNET45
            webrqst.ContentLength = qd.Length;
#endif



            var rqstStrm = await webrqst.GetRequestStreamAsync().ConfigureAwait(false);

            await rqstStrm.WriteAsync(qd, 0, qd.Length).ConfigureAwait(false);

            progress.ReportWhenNotNull(() => ProgressReport
                                       .CreateNew(RequestResponseSteps
                                                  .Requesting_N_Uploading, 1, 1));
        }
Example #4
0
        /// <summary>
        /// 请求微信接口(Async方式增加吞吐量);
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="contenttype"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public async static Task <string> RequestAsync(string url, object param, string contenttype = "application/json;charset=utf-8", string method = "post")
        {
            string responseString = string.Empty;

            System.Net.WebRequest request = System.Net.WebRequest.Create(url);
            request.ContentType = contenttype;
            request.Method      = method;
            if (param != null)
            {
                using (Stream stream = await request.GetRequestStreamAsync())
                {
                    string strJson = JsonConvert.SerializeObject(param);
                    byte[] bytes   = Encoding.UTF8.GetBytes(strJson);
                    await stream.WriteAsync(bytes, 0, bytes.Length);
                }
            }

            using (var response = (await request.GetResponseAsync()).GetResponseStream())
            {
                StreamReader reader = new StreamReader(response, Encoding.UTF8);
                responseString = reader.ReadToEnd();
            }
            return(responseString);
        }
Example #5
0
        protected override async Task FillDataTo(System.Net.WebRequest webRequest, CancellationToken cancellationToken, IProgress <ProgressReport> progress)
        {
            var memStream = new MemoryStream();

            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            //var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");

            // 设置属性

            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                "Content-Type: application/octet-stream\r\n\r\n";


            foreach (var fileKvp in RequestData.UploadFiles)
            {
                var value = fileKvp.Value;
                memStream.Write(beginBoundary, 0, beginBoundary.Length);
                var header      = string.Format(filePartHeader, fileKvp.Key, value.LocalPath);
                var headerbytes = Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);

                var stream = await value.StreamFactory.ConfigureAwait(false);

                await stream.CopyToAsync(memStream).ConfigureAwait(false);

                // await memStream.WriteAsync(beginBoundary, 0, beginBoundary.Length);

                memStream.Write(CRLFBYTES, 0, CRLFBYTES.Length);
            }

            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }
            // 写入字符串的Key


            var stringKeyHeader = "Content-Disposition: form-data; name=\"{0}\"" +
                                  "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in (
                         this.RequestData.PostFieldValues

                         .SelectMany(kvp => kvp.Value.Select(x => new { kvp.Key, Value = x }))
                         )
                     .Select(
                         keyvp =>
            {
                return(string.Format(stringKeyHeader, keyvp.Key, keyvp.Value));
            }
                         )
                     .Select
                     (
                         str => Encoding.UTF8.GetBytes(str)

                     ))
            {
                memStream.Write(beginBoundary, 0, beginBoundary.Length);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);
#if SILVERLIGHT_4 || SILVERLIGHT_5 || DOTNET45
            webRequest.ContentLength = memStream.Length;
#endif



            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }


            var requestStream = await webRequest.GetRequestStreamAsync().ConfigureAwait(false);

            memStream.Position = 0;
            //await memStream.CopyToAsync(requestStream, 512 * 1024, cancellationToken);
            var total        = memStream.Length;
            var current      = 0;
            var buffer       = new byte[4096];
            var sourceStream = memStream;
            var eof          = false;
            while (!eof)
            {
                progress.ReportWhenNotNull(() => ProgressReport.CreateNew(RequestResponseSteps.Requesting_N_Uploading, current, total));
                cancellationToken.ThrowIfCancellationRequested();
                var readCount = await sourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                current = current + readCount;

                eof = (readCount == 0);
                if (!eof)
                {
                    requestStream.Write(buffer, 0, readCount);
                }
            }

            //requestStream.Close();
        }