Ejemplo n.º 1
1
        public async Task<string> ImageToStream(byte[] image)
        {
            try
            {


                System.Diagnostics.Debug.WriteLine(image.Length);
                using (var client = new System.Net.Http.HttpClient())
                {
                    using (var content =
                        new System.Net.Http.MultipartFormDataContent())
                    {
                        content.Add(new System.Net.Http.StreamContent(new MemoryStream(image)), "file", "upload.jpg");

                        using (
                           var message =
                               await client.PostAsync("http://bbs.jiangnan.edu.cn/attachments/upload.php", content))
                        {
                            message.EnsureSuccessStatusCode();
                            string finalresults = await message.Content.ReadAsStringAsync();
                            System.Diagnostics.Debug.WriteLine(finalresults);
                            return finalresults;


                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                return e.Message;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Send a pre-serialized OFX request to the service, retrieve the response and deserialize into an OFX object.
        /// 
        /// This is an asycronous call.
        /// </summary>
        /// <param name="request">Populated OFX request object</param>
        /// <returns>The returned task includes a populated OFX response object on successfull call</returns>
        public async Task<Protocol.OFX> sendRequestAsync(StreamContent request)
        {
            // Create an HTTPClient to send the request
            using (var client = new System.Net.Http.HttpClient())
            {
                // OFX endpoints do not use 100 Continue responses. Disable default .NET expectation of them.
                client.DefaultRequestHeaders.ExpectContinue = false;

                // POST request and await response
                var response = await client.PostAsync(m_serviceURI.ToString(), request).ConfigureAwait(false);

                // Read into stream
                var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                // Deserialize XML stream into object - try directly deserializing
                try
                {
                    return (Protocol.OFX) m_serializer.Deserialize(responseStream);
                }
                catch (System.InvalidOperationException)
                {
                    // This is sometimes thrown when the response is actually UTF-8, but the xml marker claims utf-16
                    responseStream.Position = 0;
                    var streamReader = new StreamReader(responseStream, Encoding.UTF8);
                    return (Protocol.OFX)m_serializer.Deserialize(streamReader);
                }

            }
        }
 static async System.Threading.Tasks.Task Main(string[] args)
 {
     foreach (var user in System.Text.Json.JsonSerializer.Deserialize <User[]>(await System.IO.File.ReadAllTextAsync("users.json"))) // Loop through every user read from the file
     {
         if (!(await client.GetAsync($"People('{user.UserName}')")).IsSuccessStatusCode)                                             // Check if user exists
         {
             await client.PostAsync("People", new System.Net.Http.StringContent(System.Text.Json.JsonSerializer.Serialize(new { user.UserName, user.FirstName, user.LastName, Emails = new[] { user.Email }, AddressInfo = new[] { new { user.Address, City = new { Name = user.CityName, CountryRegion = user.Country, Region = "unknown" } } } }), System.Text.Encoding.UTF8, "application/json"));
         }
     }
 }
Ejemplo n.º 4
0
        public async Task<string> PostStringAsync2(string link, List<KeyValuePair<string, string>> values)
        {

            var httpClient = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler());
            System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(link), new System.Net.Http.FormUrlEncodedContent(values));
            response.EnsureSuccessStatusCode();
            var responseString = await response.Content.ReadAsStringAsync();
            System.Diagnostics.Debug.WriteLine(response.Headers);
            return responseString;
        }
Ejemplo n.º 5
0
        internal static async System.Threading.Tasks.Task <string> PostJsonAsync(string url, string requestBody, int timeout = 10000)
        {
            using (var hc = new System.Net.Http.HttpClient())
            {
                hc.Timeout = TimeSpan.FromMilliseconds(timeout);
                var data = await hc.PostAsync(url, new System.Net.Http.StringContent(requestBody, Encoding.UTF8, "application/json"));

                return(Encoding.UTF8.GetString(await data.Content.ReadAsByteArrayAsync()));
            }
        }
Ejemplo n.º 6
0
        public IActionResult Add(Guid id, [Bind("Name,FathersName,Age")] Models.Student student)
        {
            student.Id = Guid.NewGuid();
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.BaseAddress = new Uri(_configuration.GetValue <string>("AppConfig:Url"));
            System.Net.Http.ObjectContent content = new System.Net.Http.ObjectContent(typeof(Models.Student), student, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
            var result = client.PostAsync("/api/StudentService/", content).Result;

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 7
0
        async private Task <string> watchingReservation(string token, string id, string mode)
        {
            util.debugWriteLine("watching reservation post " + token + " " + mode);
            try {
                var handler = new System.Net.Http.HttpClientHandler();
                handler.UseCookies      = true;
                handler.CookieContainer = cc;
                var http = new System.Net.Http.HttpClient(handler);
                handler.UseProxy = true;
                handler.Proxy    = util.httpProxy;


                //var contentStr = "mode=auto_register&vid=" + id + "&token=" + token + "&_=";
                //util.debugWriteLine("reservation " + contentStr);

                var _content = new List <KeyValuePair <string, string> >();
                if (mode == "watching_reservation_regist")
                {
                    _content.Add(new KeyValuePair <string, string>("mode", "auto_register"));
                    _content.Add(new KeyValuePair <string, string>("vid", id));
                    _content.Add(new KeyValuePair <string, string>("token", token));
                    _content.Add(new KeyValuePair <string, string>("_", ""));
                }
                else if (mode == "regist_finished")
                {
                    _content.Add(new KeyValuePair <string, string>("accept", "true"));
                    _content.Add(new KeyValuePair <string, string>("mode", "use"));
                    _content.Add(new KeyValuePair <string, string>("vid", id));
                    _content.Add(new KeyValuePair <string, string>("token", token));
                    _content.Add(new KeyValuePair <string, string>("", ""));
                }
                //var content = new System.Net.Http.StringContent(contentStr);
                var content = new System.Net.Http.FormUrlEncodedContent(_content);
                //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                http.Timeout = TimeSpan.FromSeconds(3);
                var url = "https://live.nicovideo.jp/api/watchingreservation";
                var _t  = http.PostAsync(url, content);
                _t.Wait();
                var _res = _t.Result;
                var res  = await _res.Content.ReadAsStringAsync();

                //			var a = _res.Headers;

                //			if (res.IndexOf("login_status = 'login'") < 0) return null;

//				cc = handler.CookieContainer;

                return(res);
//				return cc;
            } catch (Exception e) {
                util.debugWriteLine("get watching exception " + e.Message + e.StackTrace);
                return(null);
            }
        }
Ejemplo n.º 8
0
        public static async Task <string> getHttpWebRequest(string api, List <KeyValuePair <String, String> > paramList = null, int PostORGet = 0, bool fulluri = false)
        {
            string content = "";

            return(await Task.Run(() =>
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                        string uri;
                        if (!fulluri)
                        {
                            uri = "http://hongyan.cqupt.edu.cn/" + api;
                        }
                        else
                        {
                            uri = api;
                        }
                        httpClient.DefaultRequestHeaders.Add("API_APP", "winphone");
                        httpClient.DefaultRequestHeaders.Add("API_TOKEN", "0zLUZA0j+OL77OsjXC0ulOz50KaI6yANZtkOk2vQIDg=");
                        System.Net.Http.HttpRequestMessage requst;
                        System.Net.Http.HttpResponseMessage response;
                        if (PostORGet == 0)
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
                            response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
                        }
                        else
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
                            response = httpClient.GetAsync(new Uri(uri)).Result;
                        }
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            content = response.Content.ReadAsStringAsync().Result;
                        }
                        //else if (response.StatusCode == HttpStatusCode.NotFound)
                        //    Utils.Message("Oh...服务器又跪了,给我们点时间修好它");
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "网络请求异常");
                    }
                }
                else
                {
                }
                //if (content.IndexOf("{") != 0)
                //    return "";
                //else
                return content;
            }));
        }
        public async Task SendAsync(string data)
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri(_uri);

                var content = new System.Net.Http.StringContent(data, Encoding.UTF8, "application/json");

                await client.PostAsync($"/write?db={_databaseName}&precision=s", content);
            }
        }
Ejemplo n.º 10
0
 public static async Task <string> GetTokenAsync()
 {
     using (var client = new System.Net.Http.HttpClient())
     {
         client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Help.PrivateKeys.ImmersiveReaderKey);
         using (var response = await client.PostAsync(Help.PrivateKeys.ImmersiveReaderEndpoint, null))
         {
             return(await response.Content.ReadAsStringAsync());
         }
     }
 }
Ejemplo n.º 11
0
        public async Task <Token> CreateAPIKey()
        {
            m_Succeed = false;
            m_Token   = new ConBee.Token()
            {
                Authorized = false
            };
            System.Net.Http.HttpClient m_HttpClient = new System.Net.Http.HttpClient();
            m_HttpClient.DefaultRequestHeaders.Add("X-HeaderKey", "HeaderValue");
            m_HttpClient.DefaultRequestHeaders.Referrer = new Uri(m_Settings.ServiceURL);

            var m_URL = "http://" + m_InternalIPAddress + ":" + m_InternalPort + "/api";

            System.Web.Script.Serialization.JavaScriptSerializer m_JsSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();

            System.Net.Http.StringContent m_StringContent =
                new System.Net.Http.StringContent(m_JsSerializer.Serialize(new { devicetype = m_Settings.APIKey, username = m_Settings.Password }));

            System.Net.Http.HttpResponseMessage m_HttpResponseMessage = await m_HttpClient.PostAsync(m_URL, m_StringContent);

            string m_Response = await m_HttpResponseMessage.Content.ReadAsStringAsync();

            if (m_HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var             m_Result      = m_JsSerializer.DeserializeObject(m_Response);
                System.Object[] m_APIKeyArray = (System.Object[])m_Result;

                System.Collections.Generic.Dictionary <string, object> m_APIKeyConfiguration =
                    (System.Collections.Generic.Dictionary <string, object>)m_APIKeyArray[0];

                try
                {
                    System.Collections.Generic.Dictionary <string, object> m_APIKey =
                        (System.Collections.Generic.Dictionary <string, object>)m_APIKeyConfiguration["success"];
                    m_Token = new Token()
                    {
                        Authorized          = true,
                        UserID              = m_APIKey["username"].ToString(),
                        APIKey              = m_Settings.APIKey,
                        InternalIPAddress   = m_InternalIPAddress,
                        InternalPort        = m_InternalPort,
                        Description         = "OK",
                        HttpResponseMessage = m_HttpResponseMessage
                    };
                }
                catch
                {
                }
                m_Succeed = true;
            }

            return(m_Token);
        }
Ejemplo n.º 12
0
        public static async Task <string> HttpClientPost(string url, string data)
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                System.Net.Http.HttpContent postContent = new System.Net.Http.StringContent(data);
                postContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var response = client.PostAsync(url, postContent).Result;

                return(await response.Content.ReadAsStringAsync());
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Exchange your Azure subscription key for an access token
 /// </summary>
 private async Task <string> GetTokenAsync()
 {
     using (var client = new System.Net.Http.HttpClient())
     {
         client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);
         using (var response = await client.PostAsync($"{Endpoint}/issueToken", null))
         {
             return(await response.Content.ReadAsStringAsync());
         }
     }
 }
Ejemplo n.º 14
0
        public async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> SendToServer(string packet, string ip = "", string port = "3000")
        {
            if (string.IsNullOrWhiteSpace(ip))
            {
                ip = GetHostLocalIp();
            }

            const string Json = "application/json";

            return(await httpClient.PostAsync($"https://{ip}:{port}/treedatas", new System.Net.Http.StringContent(packet, System.Text.Encoding.UTF8, Json)));
        }
        protected override HttpResponse PostRequest(string url, string clientIpAddress, byte[] gzippedPayload)
        {
            using (System.Net.Http.HttpClient httpClient = CreateHttpClient(clientIpAddress))
            {
                var content      = CreatePostContent(gzippedPayload);
                var responseTask = httpClient.PostAsync(url, content);
                responseTask.Wait();

                return(CreateHttpResponse(responseTask.Result));
            }
        }
Ejemplo n.º 16
0
        private RequestUploadAuthorization UploadFile(string fileUri, RequestUploadAuthorization requestUploadAuthorization = null)
        {
            if (string.IsNullOrEmpty(fileUri))
            {
                throw new ArgumentNullException("FileURI cannot be null", fileUri);
            }
            // Get local file path
            Uri uri = null; string localFilepath = null, contentType = null;

            if (Uri.TryCreate(fileUri, UriKind.RelativeOrAbsolute, out uri))
            {
                if (uri.Scheme == Uri.UriSchemeFile)
                {
                    localFilepath = uri.LocalPath;
                    contentType   = MimeTypes.MimeTypeMap.GetMimeType(Path.GetExtension(localFilepath));
                }
                else
                {
                    localFilepath = Path.Combine(Path.GetTempPath(), uri.Segments.Last());
                    using (WebClient wc = new WebClient())
                    {
                        wc.DownloadFile(uri, localFilepath);
                        contentType = wc.ResponseHeaders["Content-Type"];
                    }
                }
            }
            else
            {
                throw new ArgumentNullException("Invalid file URI", fileUri);
            }
            if (!File.Exists(localFilepath))
            {
                throw new FileNotFoundException("File not found", localFilepath);
            }
            // Get the request upload authorization
            if (requestUploadAuthorization == null)
            {
                requestUploadAuthorization = this.GetRequestUploadAuthorization(Path.GetFileName(localFilepath), contentType);
            }
            // Create the MultipartFormDataContent
            var formDataContent = new System.Net.Http.MultipartFormDataContent();

            formDataContent.Add(new System.Net.Http.StreamContent(File.OpenRead(localFilepath)), "file", requestUploadAuthorization.Filename);
            // Post the file
            var httpClient = new System.Net.Http.HttpClient();
            var result     = httpClient.PostAsync(requestUploadAuthorization.UploadURL, formDataContent);

            if (result.Result.StatusCode != System.Net.HttpStatusCode.NoContent)
            {
                throw result.Exception ?? new Exception(string.Format("Code {0} : {1}", (int)result.Result.StatusCode, result.Result.ReasonPhrase));
            }
            return(requestUploadAuthorization);
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> FileUpLoadAPI(IFormFile fileAPI)
        {
            var uploads = Path.Combine(_environment.WebRootPath, "/Temp/");

            uploads = @"C:\Projekt\tinkerMyCloud\src\tinkerMyCloud\Temp"; //TODO: relativ sökväg
            if (fileAPI == null)
            {
                throw new NotImplementedException();
            }
            else if (fileAPI.Length > 0)
            {
                byte[] array = new byte[0];
                using (var fileStream = new FileStream(Path.Combine(uploads, fileAPI.FileName), FileMode.Create))
                {
                    await fileAPI.CopyToAsync(fileStream);

                    // Skapa array
                    byte[] fileArray = new byte[fileStream.Length];

                    // konventera stream till array
                    fileStream.Read(fileArray, 0, System.Convert.ToInt32(fileStream.Length));

                    // sätt array utanför scope
                    array = fileArray;
                }

                // skicka api..
                var myfile = new FileBlob();
                myfile.Id       = 0;
                myfile.FileName = "testNshit";
                myfile.MimeType = "kgbShitTypeOfFile";
                myfile.FileData = array;

                var jsondata = JsonConvert.SerializeObject(myfile);

                var uri = new Uri("http://localhost:1729/api/Rest");

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpContent contentPost = new System.Net.Http.StringContent(jsondata, System.Text.Encoding.UTF8, "application/json");
                try
                {
                    var response = client.PostAsync(uri, contentPost);
                }
                catch (Exception)
                {
                    throw new NotImplementedException();
                }

                //TODO: tabort temp fil som sparas till stream..
            }
            return(View("Index"));
        }
        /// <summary>
        /// 网络请求接口
        /// </summary>
        /// <param name="uri">网址</param>
        /// <param name="paramList">键值对</param>
        /// <param name="PostOrGet">获取方式PostOrGet = 0 为Post;PostOrGet = 1 为Get</param>
        /// <returns></returns>
        public static async Task <string> NetworkRequest(string uri, List <KeyValuePair <String, String> > paramList = null, int PostOrGet = 0)
        {
            //返回内容
            string _content = "";

            return(await Task.Run(() =>
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                        System.Net.Http.HttpRequestMessage requst;
                        System.Net.Http.HttpResponseMessage response;

                        if (PostOrGet == 0)
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
                            response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                _content = response.Content.ReadAsStringAsync().Result;
                            }
                        }
                        else if (PostOrGet == 1)
                        {
                            string key = "";
                            string value = "";
                            string newUri = "";
                            foreach (var item in paramList)
                            {
                                key = item.Key;
                                value = item.Value;
                            }
                            //http://yangruixin.com/test/apiForText.php?RequestType=organizations
                            newUri = uri + "?" + key + "=" + value;
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
                            response = httpClient.GetAsync(new Uri(newUri)).Result;

                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                _content = response.Content.ReadAsStringAsync().Result;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "网络请求异常");
                    }
                }
                return _content;
            }));
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> RefreshToken(int userId, RefreshToken refreshToken)
        {
            var userEnt = await _userService.GetOrdUserAsync(userId);

            if (userEnt == null)
            {
                return(NotFound(new { Error = $"A user with an Id of '{userId}' could not be found." }));
            }

            var values = new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >
            {
                new System.Collections.Generic.KeyValuePair <string, string>("client_id", "orderbuddy_password"),
                new System.Collections.Generic.KeyValuePair <string, string>("client_secret", "7baeb4e4"),
                new System.Collections.Generic.KeyValuePair <string, string>("grant_type", "refresh_token"),
                new System.Collections.Generic.KeyValuePair <string, string>("refresh_token", refreshToken.Token)
            };

            var formEnCoded = new System.Net.Http.FormUrlEncodedContent(values);

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

                var response = await httpClient.PostAsync("https://accounts.orderbuddy.co.za/connect/token", formEnCoded); // URL will change to accounts.orderbuddy.co.za

                if (response != null)
                {
                    var httpStringContent = await response.Content.ReadAsStringAsync();

                    var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(httpStringContent);

                    if (responseObject != null)
                    {
                        if (responseObject.error != null)
                        {
                            return(BadRequest(new { Error = "Invalid token." }));
                        }

                        var token = new
                        {
                            AccessToken  = responseObject.access_token,
                            RefreshToken = responseObject.refresh_token,
                            ExpiresIn    = responseObject.expires_in
                        };

                        return(Ok(token));
                    }
                }
            }

            return(BadRequest(new { Error = "Could not refresh token." }));
        }
Ejemplo n.º 20
0
        private async Task <IDictionary <string, object> > SendHttpRequest(TRootMessage rootMessage, bool isPollConnection)
        {
            ASSERT((rootMessage != null) && (rootMessage.Count > 0), "Missing parameter 'rootMessage'");
            ASSERT(!string.IsNullOrWhiteSpace(HandlerUrl), "Property 'HandlerUrl' is supposed to be set here");

            string strResponse;

            try
            {
                using (var handler = new System.Net.Http.HttpClientHandler()
                {
                    CookieContainer = Cookies
                })
                    using (var client = new System.Net.Http.HttpClient(handler)
                    {
                        Timeout = System.Threading.Timeout.InfiniteTimeSpan
                    })
                    {
                        if (isPollConnection)
                        {
                            ASSERT(PollClient == null, "Property 'PollClient' is not supposed to be set here");
                            PollClient = client;

                            var status = Status;
                            switch (status)
                            {
                            case ConnectionStatus.Closing:
                            case ConnectionStatus.Disconnected:
                                throw new ArgumentException("Cannot create new connection while status is '" + status + "'");
                            }
                        }

                        var strMessage = rootMessage.ToJSON();
                        var content    = new System.Net.Http.StringContent(strMessage, Encoding.UTF8, "application/json");
                        var response   = await client.PostAsync(HandlerUrl, content);

                        LOG("Receive response content");
                        strResponse = await response.Content.ReadAsStringAsync();
                    }
            }
            finally
            {
                if (isPollConnection)
                {
                    ASSERT(PollClient != null, "Property 'PollClient' is supposed to be set here");
                    PollClient = null;
                }
            }
            var responseMessage = strResponse.FromJSONDictionary();

            return(responseMessage);
        }
Ejemplo n.º 21
0
        private void callAPI(string daisha, string location)
        {
            var APIContent = new System.Net.Http.StringContent("login=admin&password=r4pyd&model=agv.checkpoint&values= {\"daisha\": \"" + daisha + "\", \"location\": \"" + location + "\"}", Encoding.UTF8, "application/x-www-form-urlencoded");
            var client     = new System.Net.Http.HttpClient();
            var response   = client.PostAsync("https://hppm-wms.herokuapp.com/api/create", APIContent).Result;

            if (response.IsSuccessStatusCode)
            {
                var     responseString = response.Content.ReadAsStringAsync().Result;
                dynamic json           = JsonConvert.DeserializeObject(responseString);
                Console.WriteLine(json);
            }
        }
Ejemplo n.º 22
0
        private async Task <string> FetchToken(string fetchUri, string subscriptionKey)
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
                UriBuilder uriBuilder = new UriBuilder(fetchUri);
                uriBuilder.Path += "/issueToken";

                var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null);

                return(await result.Content.ReadAsStringAsync());
            }
        }
Ejemplo n.º 23
0
        public async static Task <string> PostJsonForString(string url, Dictionary <string, string> body)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();//new ModernHttpClient.NativeMessageHandler());
            var json     = JsonConvert.SerializeObject(body);
            var content  = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(url, content);

            string jsonText = "";

            jsonText = await response.Content.ReadAsStringAsync();

            return(jsonText);
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> ScanPdf417(string blobRef, [FromQuery] bool?raw = false, [FromQuery] bool?veh = false, [FromQuery] bool?drv = false)
        {
            var res = this.Response;
            var req = this.Request;

            try
            {
                // always start off not caching whatever we send back
                res.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0";
                res.Headers["Pragma"]        = "no-cache"; // HTTP 1.0.
                res.Headers["Content-Type"]  = "application/json";

                if (!BlobStore.Exists(blobRef))
                {
                    return(NotFound($"Invalid, non-existent or expired blob reference specified: '{blobRef}'"));
                }

                var blobData = BlobStore.Get(blobRef);

                var client = new System.Net.Http.HttpClient();

                using (var content = new System.Net.Http.ByteArrayContent(blobData.Data))
                {
                    var barcodeServiceUrl = this.config["AppSettings:BarcodeService.URL"].TrimEnd('/');
                    var postUrl           = $"{barcodeServiceUrl}/scan/pdf417?raw={raw}&veh={veh}&drv={drv}";

                    var response = await client.PostAsync(postUrl, content);

                    var responseText = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var json = JsonConvert.DeserializeObject(responseText);

                        return(Ok(ApiResponse.Payload(json)));
                    }
                    else
                    {
                        SessionLog.Error("Barcode failed. postUrl = {0}; contentLength: {1}; responseText={2}", postUrl ?? "(null)", blobData?.Data?.Length ?? -1, responseText ?? "(null)");

                        //return StatusCode((int)response.StatusCode, responseText);
                        //return new ContentResult() { Content = responseText, StatusCode = (int)response.StatusCode, ContentType = "text/plain" };
                        return(BadRequest(responseText));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Ok(ApiResponse.Exception(ex)));
            }
        }
Ejemplo n.º 25
0
        public async Task PostAsync_Upload_Regular_FileNameAsync()
        {
            await _client.LogInAsync();

            var response = await _client.PostAsync(_uri.Path + "/upload", HttpClientExtensions.CreateJsonString(_doc1));

            response.EnsureSuccessStatusCode();
        }
Ejemplo n.º 26
0
        static string Post(string path, Dictionary <string, string> dict)
        {
            var httpClient = new System.Net.Http.HttpClient();

            httpClient.BaseAddress = new Uri(BaseURL);
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var body = new System.Net.Http.FormUrlEncodedContent(dict);

            // response
            var response = httpClient.PostAsync(path, body).Result;
            var data     = response.Content.ReadAsStringAsync().Result;

            return(data);
        }
Ejemplo n.º 27
0
        public async Task <string> PostHttpDataAsync(string url, System.Net.Http.HttpContent postdata)
        {
            var httpClient = new System.Net.Http.HttpClient();
            var response   = await httpClient.PostAsync(url, postdata);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(await response.Content.ReadAsStringAsync());//加await的意思是说,主UI等待它执行完成后,再继续执行,这种就叫作并行!
            }
            else
            {
                return(null);//error
            }
        }
Ejemplo n.º 28
0
 public void SendHttpRequest(string uri, string payload, Logger logger)
 {
     try
     {
         (payload == null ?
          Client.GetAsync(uri) :
          Client.PostAsync(uri, new System.Net.Http.StringContent(payload, null, PayloadContentType)))
         .GetAwaiter().GetResult().EnsureSuccessStatusCode();
     }
     catch (System.Exception exception)
     {
         Logger.Log("HTTP request failed: " + exception + " (URI: " + uri + ")");
     }
 }
Ejemplo n.º 29
0
        async public Task <string> getWatching()
        {
            util.debugWriteLine("watching post" + util.getMainSubStr(isSub, true));
            try {
                var handler = new System.Net.Http.HttpClientHandler();
                handler.UseCookies      = true;
                handler.CookieContainer = container;
                var http = new System.Net.Http.HttpClient(handler);
                handler.UseProxy = false;
                http.DefaultRequestHeaders.Add("X-Frontend-Id", "91");
                http.DefaultRequestHeaders.Add("X-Connection-Environment", "ethernet");
                http.DefaultRequestHeaders.Add("Host", "api.cas.nicovideo.jp");
                http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
                http.DefaultRequestHeaders.Add("Accept", "application/json");

//				var contentStr = "{\"actionTrackId\":\"" + actionTrackId + "\",\"streamProtocol\":\"rtmp\",\"streamQuality\":\"" + requestQuality + "\"";
                var contentStr = "{\"actionTrackId\":\"" + actionTrackId + "\",\"streamProtocol\":\"https\",\"streamQuality\":\"" + requestQuality + "\"";
                if (streamCapacity != "ultrahigh")
                {
                    contentStr += ", \"streamCapacity\":\"" + streamCapacity + "\"";
                }
                if (isLive)
                {
                    contentStr += ",\"isBroadcaster\":" + isBroadcaster.ToString().ToLower() + ",\"isLowLatencyStream\":false";
                }
                contentStr += "}";
                util.debugWriteLine(contentStr + util.getMainSubStr(isSub, true));

                var content = new System.Net.Http.StringContent(contentStr);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                http.Timeout = TimeSpan.FromSeconds(5);
                var _t = http.PostAsync(watchingUrl, content);
                _t.Wait();
                var _res = _t.Result;
                var res  = await _res.Content.ReadAsStringAsync();

                //			var a = _res.Headers;

                //			if (res.IndexOf("login_status = 'login'") < 0) return null;

//				cc = handler.CookieContainer;

                return(res);
//				return cc;
            } catch (Exception e) {
                util.debugWriteLine("get watching exception " + e.Message + e.StackTrace + util.getMainSubStr(isSub, true));
                return(null);
            }
        }
Ejemplo n.º 30
0
        } // End Sub Post

        public async System.Threading.Tasks.Task <int?> Get()
        {
            System.Collections.Generic.List <PersonModel> people =
                new System.Collections.Generic.List <PersonModel>
            {
                new PersonModel
                {
                    FirstName = "Test",
                    LastName  = "One",
                    Age       = 25
                },
                new PersonModel
                {
                    FirstName = "Test",
                    LastName  = "Two",
                    Age       = 45
                }
            };

            using (System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler())
            {
                handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler, false))
                {
                    string json               = Newtonsoft.Json.JsonConvert.SerializeObject(people);
                    byte[] jsonBytes          = System.Text.Encoding.UTF8.GetBytes(json);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    using (System.IO.Compression.GZipStream gzip =
                               new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
                    {
                        gzip.Write(jsonBytes, 0, jsonBytes.Length);
                    }
                    ms.Position = 0;
                    System.Net.Http.StreamContent content = new System.Net.Http.StreamContent(ms);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    content.Headers.ContentEncoding.Add("gzip");
                    System.Net.Http.HttpResponseMessage response = await client.PostAsync("http://localhost:54425/api/Gzipping", content);

                    // System.Collections.Generic.IEnumerable<PersonModel> results = await response.Content.ReadAsAsync<System.Collections.Generic.IEnumerable<PersonModel>>();
                    string result = await response.Content.ReadAsStringAsync();

                    System.Collections.Generic.IEnumerable <PersonModel> results = Newtonsoft.Json.JsonConvert.
                                                                                   DeserializeObject <System.Collections.Generic.IEnumerable <PersonModel> >(result);

                    System.Diagnostics.Debug.WriteLine(string.Join(", ", results));
                }
            }

            return(null);
        }
Ejemplo n.º 31
0
        public static async Task<string> getHttpWebRequest(string api, List<KeyValuePair<String, String>> paramList = null, int PostORGet = 0, bool fulluri = false)
        {
            string content = "";
            return await Task.Run(() =>
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                        string uri;
                        if (!fulluri)
                            uri = "http://hongyan.cqupt.edu.cn/" + api;
                        else
                            uri = api;
                        httpClient.DefaultRequestHeaders.Add("API_APP", "winphone");
                        httpClient.DefaultRequestHeaders.Add("API_TOKEN", "0zLUZA0j+OL77OsjXC0ulOz50KaI6yANZtkOk2vQIDg=");
                        System.Net.Http.HttpRequestMessage requst;
                        System.Net.Http.HttpResponseMessage response;
                        if (PostORGet == 0)
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
                            response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
                        }
                        else
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
                            response = httpClient.GetAsync(new Uri(uri)).Result;
                        }
                        if (response.StatusCode == HttpStatusCode.OK)
                            content = response.Content.ReadAsStringAsync().Result;
                        //else if (response.StatusCode == HttpStatusCode.NotFound)
                        //    Utils.Message("Oh...服务器又跪了,给我们点时间修好它");

                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "网络请求异常");
                    }
                }
                else
                {
                }
                //if (content.IndexOf("{") != 0)
                //    return "";
                //else
                return content;

            });
        }
Ejemplo n.º 32
0
        async System.Threading.Tasks.Task<bool> MakeTheCallAsync()
        {
            string caller = PhoneNumbers[FromNumber];
            if (caller == null)
                throw new ArgumentException(FromNumber.ToString(), "FromNumber");
            if (String.IsNullOrEmpty(ToNumber))
                throw new ArgumentException(ToNumber ?? "null", "ToNumber");
            string xml = null;
            if (1 < NRepeatAll)
            {

                var say = new System.Xml.XmlDocument().CreateElement("Say");
                say.InnerText = Message;
                xml = "<Response>" + String.Join("<Pause length=\"2\"/>", Enumerable.Repeat(say.OuterXml, NRepeatAll)) + "</Response>";
            }

            var client = new System.Net.Http.HttpClient();  // System.Net.Http.dll
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(TwilioSid + ":" + TwilioToken)));
            try
            {
                System.Net.Http.HttpResponseMessage response = await client.PostAsync(
                    "https://api.twilio.com/2010-04-01/Accounts/" + TwilioSid + "/Calls.json",  // could be .csv as well, see https://www.twilio.com/docs/api/rest/tips
                    new System.Net.Http.FormUrlEncodedContent(new Dictionary<string, string>() {
                        { "From", caller },
                        { "To",   ToNumber },
                        { "Method", "GET" },
                        { "Url",  xml != null ? "http://twimlets.com/echo?Twiml=" + Uri.EscapeDataString(xml)
                                              : "http://twimlets.com/message?Message%5B0%5D=" + Uri.EscapeDataString(Message) }   // O.K.
                        //{ "Url",  "http://twimlets.com/message?" + Uri.EscapeDataString("Message[0]=" + p_message) } // <Response/>  -- successful but empty call
                        //{ "Url",  "http://twimlets.com/message?Message%5B0%5D=Hello+this+is+a+test+call+from+Twilio." }  // O.K.
                        //{ "Url",  "http://twimlets.com/message?Message[0]=Hello%2C+this+is+a+test+call+from+Twilio." }  // Error: 11100 Invalid URL format 
                        //{ "Url",  "http://twimlets.com/message?Message[0]=Hello,+this+is+a+test+call+from+Twilio." }  // Error: 11100 Invalid URL format 
                        //{ "Url",  "http://twimlets.com/message?Message[0]=" + Uri.EscapeDataString(p_message) } // Error: 11100 Invalid URL format 
                        //{ "Url",  "http://www.snifferquant.com/robin/twimlet.xml" }  // O.K.
                    }));
                string resp = await response.Content.ReadAsStringAsync();
                if (resp.StartsWith("{\"sid\":"))
                    ResultJSON = resp;
                else
                    Error = resp;
            }
            catch (Exception e)
            {
                Error = ToStringWithoutStackTrace(e);
                //Program.gLogger.Info("Error: " + Error);
                Console.WriteLine("Error: " + Error);
            }
            return Error == null;
        }
Ejemplo n.º 33
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            string applicationId = "2a4dbf13-4a77-471a-8519-a8bd56f85728";
            string redirectUri   = "urn:ietf:wg:oauth:2.0:oob";
            string scopes        = "https://graph.microsoft.com/User.Read openid offline_access";

            string authorizeUri = string.Format("https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={0}&response_type=code&redirect_uri={1}&scope={2}", applicationId, redirectUri, scopes);
            string tokenUri     = "https://login.microsoftonline.com/common/oauth2/v2.0/token";

            WebAuthenticationResult WebAuthenticationResult =
                await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    new Uri(authorizeUri),
                    new Uri(redirectUri));

            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                // Parse out the auth code from the response
                string authorization_code = WebAuthenticationResult.ResponseData.ToString().Split('=')[1].Split('&')[0];

                // Buld a data set to send to the Token URI for processing
                var data = new Dictionary <string, string>();
                data.Add("grant_type", "authorization_code");
                data.Add("code", authorization_code);
                data.Add("client_id", applicationId);
                data.Add("redirect_uri", redirectUri);
                data.Add("scope", scopes);

                // Create an HTTP Client
                var client = new System.Net.Http.HttpClient();

                // Post the data we compiled above to the TokenURI
                var result = await client.PostAsync(tokenUri, new System.Net.Http.FormUrlEncodedContent(data));

                // This next part is only for the demo. It the JSON object returned by the TokenURI
                // and converts it to a raw string. We then copy it to the UI so you can see the results
                var tokenObject = await result.Content.ReadAsStringAsync();

                this.resultText.Text = tokenObject;
            }
            else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                this.resultText.Text = "HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString();
            }
            else
            {
                this.resultText.Text = "Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString();
            }
        }
Ejemplo n.º 34
0
 public static async Task<string> getTransaction(string api, List<KeyValuePair<string, string>> paramList)
 {
     return await Task.Run(() =>
     {
         string content = "";
         System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
         System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(new Uri(api), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
         if (response.StatusCode == HttpStatusCode.OK)
         {
             content = response.Content.ReadAsStringAsync().Result;
             Debug.WriteLine(content);
         }
         return content;
     });
 }
Ejemplo n.º 35
0
        /// <summary>
        /// 通过 POST 提交某些内容到服务器,并读取响应结果; 默认下将使用 utf8 编解码;
        /// 注意,content-type 为 application/x-www-form-urlencoded;
        /// 即将 请求参数编码为 client_id=testclient&client_secret=testclientsecret 的形式并 Post
        /// </summary>
        /// <param name="url">提交的url</param>
        /// <param name="postContent">需要提交的内容</param>
        /// <returns></returns>
        public static async Task <T> FormUrlEncodedPostGetResult <T>(string url, IEnumerable <KeyValuePair <string, string> > postContent)
        {
            System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(postContent);
            content.Headers.Add("conent-type", "application/x-www-form-urlencoded");
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var asyncResult = await client.PostAsync(url, content);

            var result = await asyncResult.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(result))
            {
                return(default(T));
            }
            return(JsonConvert.DeserializeObject <T>(result));
        }
        public async Task CompressedRequestHandler_PostAsync_WorksWithNullContent()
        {
            var requestUriString = "http://sometestdomain.com/someendpoint";

            var mh = new MockMessageHandler();

            mh.AddFixedResponse("POST", new Uri(requestUriString), new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created));

            var handler = new CompressedRequestHandler(mh);
            var client  = new System.Net.Http.HttpClient(handler);

            var result = await client.PostAsync(requestUriString, null).ConfigureAwait(false);

            result.EnsureSuccessStatusCode();
        }
Ejemplo n.º 37
0
        protected override string GetAccessToken(string authCode)
        {
            System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient();

            string postData = "code={0}&client_id={1}&redirect_uri={2}&grant_type={3}&client_secret={4}";
            postData = string.Format(postData,
                HttpUtility.UrlEncode(authCode),
                CLIENT_ID,
                HttpUtility.UrlEncode(CALLBACK_URL),
                "authorization_code",
                SECRET);

            System.Net.Http.HttpResponseMessage msg = wc.PostAsync(GET_TOKEN_URL, new System.Net.Http.StringContent(postData, Encoding.Default, "application/x-www-form-urlencoded")).Result;

            if (msg.StatusCode == System.Net.HttpStatusCode.OK)
                return msg.Content.ReadAsStringAsync().Result.Replace("access_token=", "");

            return null;
        }
Ejemplo n.º 38
0
        private static void do_reportBuildShip(int dockid, BSLOG bSLOG, GetShipData getShipData)
        {
            if (getShipData == null || getShipData.shipVO == null )
            {
                return;
            }
            var dic = new Dictionary<string, string>();
            string desc = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[0].ships[0]);
            UserShip us = getShipData.shipVO;
            {
                desc += bSLOG.oil.ToString() + "|" +
                    bSLOG.ammo.ToString() + "|" +
                    bSLOG.steel.ToString() + "|" +
                    bSLOG.al.ToString() + "|" +
                    bSLOG.timetick.ToString() + "|" +
                    bSLOG.buildreturntype.ToString()  +

                    "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                    + "|" + ServerTimer.GetNowServerTime()
                    + "|" + z.instance.getServerName()
                    + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                    + "|" + GameData.instance.UserInfo.detailInfo.collection
                    + "|" + GameData.instance.UserInfo.level
                    + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportbuild", c).Result;
            }
            catch (Exception)
            {

            }
        }
Ejemplo n.º 39
0
        public static async Task<String> PasteCard(Card c)
        {
            var httpclient = new System.Net.Http.HttpClient();
            var content = new System.Net.Http.MultipartFormDataContent();
            Dictionary<String, String> formData = new Dictionary<String, String>();

            content.Add(new System.Net.Http.StringContent(API_KEY), "api_dev_key");
            content.Add(new System.Net.Http.StringContent("paste"), "api_option");
            content.Add(new System.Net.Http.StringContent(String.Format("Debug data for {0}", c.Name)), "api_paste_name");
            content.Add(new System.Net.Http.StringContent(String.Format("Source: {0}\n\n{1}", c.XmlSource, c.XmlData)), "api_paste_code");
            
            
            var response = await httpclient.PostAsync("http://pastebin.com/api/api_post.php", content);

            if (!response.IsSuccessStatusCode)
                return null;

            return await response.Content.ReadAsStringAsync();


         //   var request = System.Net.HttpWebRequest.Create("http://pastebin.com/api/api_post.php");
           // request.Method = "POST";
        }
Ejemplo n.º 40
0
        public static void SendToApi()
        {
            string[] uploadfiles = new string[] { "D:\\2d.jpg", "d:\\140317.ajk" }; //上传文件路径
            string url = "http://localhost:49840//api/fileapi"; //服务地址

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                using (var content = new System.Net.Http.MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
                {
                    //循环添加文件至列表
                    foreach (var path in uploadfiles)
                    {
                        var fileContent = new System.Net.Http.ByteArrayContent(System.IO.File.ReadAllBytes(path));
                        fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                        {
                            FileName = System.IO.Path.GetFileName(path),//此处可以自定义文件名
                        };
                        content.Add(fileContent);
                    }
                    var result = client.PostAsync(url, content).Result;//提交post请求
                }

            }
        }
Ejemplo n.º 41
0
        protected virtual string GetAccessToken(string authCode)
        {
            System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient();

            string postData = "code={0}&client_id={1}&redirect_uri={2}&grant_type={3}&client_secret={4}";
            postData = string.Format(postData,
                HttpUtility.UrlEncode(authCode),
                CLIENT_ID,
                HttpUtility.UrlEncode(CALLBACK_URL),
                "authorization_code",
                SECRET);

            System.Net.Http.HttpResponseMessage msg = wc.PostAsync(GET_TOKEN_URL, new System.Net.Http.StringContent(postData, Encoding.Default, "application/x-www-form-urlencoded")).Result;

            if (msg.StatusCode == System.Net.HttpStatusCode.OK) {
                string json = msg.Content.ReadAsStringAsync().Result;
                dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
                return data["access_token"];
            }
            return null;
        }
Ejemplo n.º 42
0
        private async void logins_Click(object sender, RoutedEventArgs e)
        {
			//try
			//{
			//	StorageFolder folder = ApplicationData.Current.LocalCacheFolder;
			//	var imgfile = await folder.GetFileAsync("ValidateCode.jpg");
			//	await imgfile.DeleteAsync();
			//}
			//catch (Exception ex)
			//{
			//	;
			//}



            Uri login = new Uri("http://222.30.32.10/stdloginAction.do");
            string parma = "operation=&usercode_text="+user.Text+"&userpwd_text="+pwd.Password+"&checkcode_text=" + vldcode.Text + "&submittype=%C8%B7+%C8%CF";
            System.Net.Http.HttpContent hc = new System.Net.Http.StringContent(parma, System.Text.UnicodeEncoding.UTF8, "application/x-www-form-urlencoded");
            System.Net.Http.HttpClient connlogin = new System.Net.Http.HttpClient();
            connlogin.DefaultRequestHeaders.Add("cookie", this.cookie);
            System.Net.Http.HttpResponseMessage res = await connlogin.PostAsync(login, hc);
            byte[] resbyte = res.Content.ReadAsByteArrayAsync().Result;
            string posts = TextReader.GBK.gbk2utf16(resbyte);

            if (posts.IndexOf("请输入正确的验证码!") != -1)
			{
				await new MessageDialog("请输入正确的验证码!").ShowAsync();
				vldcode.Text = "";
			}
                
            else if (posts.IndexOf("用户不存在或密码错误!") != -1)
			{
				await new MessageDialog("用户名不存在或密码错误").ShowAsync();
				user.Text = "";
				pwd.Password = "";
				vldcode.Text = "";
			}
                
            else
            {
                await new MessageDialog("登录成功").ShowAsync();
                ApplicationData.Current.LocalSettings.Values["login"] = true;
                ApplicationData.Current.LocalSettings.Values["cookie"] = this.cookie;
				this.Frame.Navigate(typeof(MainPage));
            }
                
            
        }
Ejemplo n.º 43
0
        public static void CaptureAsJPEG()
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
                var pageRequestJson = new System.Net.Http.StringContent(File.ReadAllText("request.json"));
                var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
                var responseStream = response.Content.ReadAsStreamAsync().Result;
                //using (var fileStream = new FileStream("content123455.jpg", FileMode.Create))
                //{
                //    responseStream.CopyTo(fileStream);
                //}

                using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                {
                    string retString = myStreamReader.ReadToEnd();
                }

                var ms = new MemoryStream();
                responseStream.CopyTo(ms);
                //responseStream.Position = 0;
                //byte[] buffer = new byte[2048];
                //int bytesRead = 0;
                //while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0)
                //{
                //    ms.Write(buffer, 0, bytesRead);
                //}
                ms.Position = 0;
                Bitmap destBmp = new Bitmap(ms);//create bmp instance from stream above
                destBmp.Save(@"D:\work\He\CommonTest\PhantomJsConsole\bin\Debug\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg");//save bmp to the path you want

                //var image = System.Drawing.Image.FromStream(ms);
                //image.Save(@"D:\work\He\CommonTest\PhantomJsConsole\bin\Debug\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg");
                //ms.Close();

                Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
                Console.WriteLine(response.Headers);
            }
        }
Ejemplo n.º 44
0
    /// <summary>
    /// POST JSON data to the specified mongoDB collection.
    /// </summary>
    async void PostJsonDataAsyncAttempt(
      string collection_name,
      string json )
    {
      using( System.Net.Http.HttpClient httpClient
        = new System.Net.Http.HttpClient() )
      {
        try
        {
          string resourceAddress = Util.RestApiUri
            + "/" + collection_name;

          string postBody = json;

          httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue(
              "application/json" ) );

          HttpResponseMessage wcfResponse
            = await httpClient.PostAsync(
              resourceAddress, new StringContent(
                postBody, Encoding.UTF8,
                "application/json" ) );

          //await DisplayTextResult( wcfResponse, OutputField );
        }
        catch( HttpRequestException hre )
        {
          Util.Log( "Error:" + hre.Message );
        }
        catch( TaskCanceledException )
        {
          Util.Log( "Request canceled." );
        }
        catch( Exception ex )
        {
          Util.Log( ex.Message );
        }
      }
    }
Ejemplo n.º 45
0
 /// <summary>
 /// 调用第三方PhantomJs
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void button3_Click(object sender, EventArgs e)
 {
     using (var client = new System.Net.Http.HttpClient())
     {
         client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
         var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
         var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
         var responseStream = response.Content.ReadAsStreamAsync().Result;
         using (var fileStream = new System.IO.FileStream("content.jpg", System.IO.FileMode.Create))
         {
             responseStream.CopyTo(fileStream);
         }
         Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
         Console.WriteLine(response.Headers);
     }
 }
Ejemplo n.º 46
0
        public IActionResult Authorized(string code)
        {
            OauthInfo oai = OauthRepository.Get();

            if (code == null)
                return View(oai);

            oai.authCode = code;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            var url = "https://graph.api.smartthings.com/oauth/token";

            List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
            parms.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
            parms.Add(new KeyValuePair<string, string>("code", oai.authCode));
            parms.Add(new KeyValuePair<string, string>("client_id", oai.clientKey));
            parms.Add(new KeyValuePair<string, string>("client_secret", oai.secretKey));
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");
            parms.Add(new KeyValuePair<string, string>("redirect_uri", authorizedUrl));

            var content = new System.Net.Http.FormUrlEncodedContent(parms);
            var response = client.PostAsync(url, content);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get Auth Code Error: " + response.Result.StatusCode.ToString());
                return View(oai);
            }

            // Save the interim result
            var val = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Result.Content.ReadAsStringAsync().Result);
            oai.accessToken = val["access_token"];
            oai.expiresInSeconds = Convert.ToInt32(val["expires_in"]);
            oai.tokenType = val["token_type"];
            OauthRepository.Save(oai);

            // Get the endpoint info
            client = new System.Net.Http.HttpClient();
            url = "https://graph.api.smartthings.com/api/smartapps/endpoints";

            System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            msg.Headers.Add("Authorization", $"Bearer {oai.accessToken}");

            response = client.SendAsync(msg);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get EndPoints Error: " + response.Result.StatusCode.ToString());
                return View(oai);
            }

            string jsonString = response.Result.Content.ReadAsStringAsync().Result;
            oai.endpoints = JsonConvert.DeserializeObject<List<OauthEndpoint>>(jsonString);

            OauthRepository.Save(oai);

            // Install the Zones
            SmartThingsRepository.InstallDevices(this.Request.Host.Value);
            return View(oai);

        }
Ejemplo n.º 47
0
        private static void do_reportGotShip(GetBattleResultResponse battleResult, int battle_fleetid, string level, string nodeflag)
        {
            if(battleResult == null || battleResult.newShipVO == null || battleResult.newShipVO.Length ==0)
            {
                return;
            }
            var dic = new Dictionary<string, string>();
            string desc = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[battle_fleetid -1].ships[0]);
            foreach(UserShip us in battleResult.newShipVO)
            {
                desc += level + "|" + nodeflag + "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                    + "|" + ServerTimer.GetNowServerTime()
                    + "|" + z.instance.getServerName()
                    + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                    + "|" + (WarResultLevel)battleResult.warResult.resultLevel
                    + "|" + battleResult.bossHpLeft
                    + "|" + GameData.instance.UserInfo.detailInfo.collection
                    + "|" + GameData.instance.UserInfo.level
                    + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportdrop", c).Result;
            }
            catch (Exception)
            {

            }
        }
        private static void DownloadDataAsync(string method, string baseUrl, string data, string contentType,
                                              string authHeader, Action<FlickrResult<string>> callback)
        {
            #if NETFX_CORE
            var client = new System.Net.Http.HttpClient();
            if (!String.IsNullOrEmpty(contentType)) client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", contentType);
            if (!String.IsNullOrEmpty(authHeader)) client.DefaultRequestHeaders.Add("Authorization", authHeader);

            if (method == "POST")
            {
                var content = client.PostAsync(baseUrl, new System.Net.Http.StringContent(data, System.Text.Encoding.UTF8, contentType)).Result.Content;
                var stringContent = content as System.Net.Http.StringContent;
                var result = new FlickrResult<string> {Result = content.ReadAsStringAsync().Result};
                callback(result);
            }
            else
            {
                var content = client.GetStringAsync(baseUrl).Result;
                var result = new FlickrResult<string> {Result = content};
                callback(result);
            }
            #else
            var client = new WebClient();
            if (!String.IsNullOrEmpty(contentType)) client.Headers["Content-Type"] = contentType;
            if (!String.IsNullOrEmpty(authHeader)) client.Headers["Authorization"] = authHeader;

             if (method == "POST")
            {
                client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e)
                                                    {
                                                        var result = new FlickrResult<string>();
                                                        if (e.Error != null)
                                                        {
                                                            result.Error = e.Error;
                                                            callback(result);
                                                            return;
                                                        }

                                                        result.Result = e.Result;
                                                        callback(result);
                                                        return;
                                                    };

                client.UploadStringAsync(new Uri(baseUrl), data);
            }
            else
            {
                client.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
                                                      {
                                                          var result = new FlickrResult<string>();
                                                          if (e.Error != null)
                                                          {
                                                              result.Error = e.Error;
                                                              callback(result);
                                                              return;
                                                          }

                                                          result.Result = e.Result;
                                                          callback(result);
                                                          return;
                                                      };

                client.DownloadStringAsync(new Uri(baseUrl));
            }
            #endif
        }
Ejemplo n.º 49
0
        public static object Request(object request, Type responseType=null, bool post=false)
        {
            /** determine the api method to call */
            string method = Mozu.getMethod(request);
            if (responseType == null) responseType = request.GetType();

            /** make sure we have a valid authentication ticket */
            if (_auth == null && request.GetType() != typeof(AuthenticationContract)) Mozu.authenticate();

            string url = string.Format("{0}{1}", _apiUrl, method);
            Type t = request.GetType();
            bool get = false;
            if (! post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
                url = "https://t7949.sandbox.mozu.com";
                get = true;
            }
            else if (post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
                url = "https://t7949.sandbox.mozu.com/api/platform";
            }
            //HTTP http = new HTTP();
            Console.WriteLine("Calling Mozu API: " + url);
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient { BaseAddress = new Uri(url) };
            //if (request.GetType() != typeof(AuthenticationContract)) http.AddHeader("x-vol-app-claims", _auth.Ticket.AccessToken);
            if (t != typeof(AuthenticationContract)) {
                client.DefaultRequestHeaders.Add("x-vol-app-claims", _auth.Ticket.AccessToken);
                client.DefaultRequestHeaders.Add("x-vol-tenant", "7949");//the sandbox number
                if (t == typeof(Product)) {
                    client.DefaultRequestHeaders.Add("x-vol-master-catalog", "2");
                }
                //client.DefaultRequestHeaders.Add("x-vol-catalog", "1");
                //client.DefaultRequestHeaders.Add("x-vol-version", "1.9.14232.3");
            }

            string json = JSON.Serialize(request);

            //string response = http.POSTRaw(url, json, "application/json");

            string response = null;
            if (get) {
                method = "/api" + method;
                if (t == typeof(Product)) method += "?startindex=0&pagesize=200";
                var r = client.GetAsync(method).Result;
                response = r.Content.ReadAsStringAsync().Result;
            }
            else {
                var r = client.PostAsync("/api" + method, new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
                response = r.Content.ReadAsStringAsync().Result;
            }

            object o = JSON.Deserialize(response, responseType);
            return o;
        }