public PostAsync ( |
||
requestUri | ||
content | ||
return | Task |
public async Task<Result> PostData(Uri uri, MultipartContent header, StringContent content) { var httpClient = new HttpClient(); try { if (!string.IsNullOrEmpty(AuthenticationToken)) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken); } HttpResponseMessage response; if (header == null) { if(content == null) content = new StringContent(string.Empty); response = await httpClient.PostAsync(uri, content); } else { response = await httpClient.PostAsync(uri, header); } var responseContent = await response.Content.ReadAsStringAsync(); return new Result(response.IsSuccessStatusCode, responseContent); } catch (Exception ex) { throw new WebException("Kinder Chat API Error: Service error", ex); } }
private async Task RunAsync(string url) { HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = new CookieContainer(); using (var httpClient = new HttpClient(handler)) { var loginUrl = url + "Account/Login"; _traceWriter.WriteLine("Sending http GET to {0}", loginUrl); var response = await httpClient.GetAsync(loginUrl); var content = await response.Content.ReadAsStringAsync(); var requestVerificationToken = ParseRequestVerificationToken(content); content = requestVerificationToken + "&UserName=user&Password=password&RememberMe=false"; _traceWriter.WriteLine("Sending http POST to {0}", loginUrl); response = await httpClient.PostAsync(loginUrl, new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded")); content = await response.Content.ReadAsStringAsync(); requestVerificationToken = ParseRequestVerificationToken(content); await RunPersistentConnection(url, httpClient, handler.CookieContainer, requestVerificationToken); await RunHub(url, httpClient, handler.CookieContainer, requestVerificationToken); _traceWriter.WriteLine(); _traceWriter.WriteLine("Sending http POST to {0}", url + "Account/LogOff"); response = await httpClient.PostAsync(url + "Account/LogOff", CreateContent(requestVerificationToken)); _traceWriter.WriteLine("Sending http POST to {0}", url + "Account/Logout"); response = await httpClient.PostAsync(url + "Account/Logout", CreateContent(requestVerificationToken)); } }
public async Task<bool> CallWebApiAddReunion(Reunion reunion, ObservableCollection<Anime> selectedAnime) { HttpClient client = new HttpClient(); string json = JsonConvert.SerializeObject(reunion); HttpContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("http://scoutome.azurewebsites.net/api/reunions", content); if (response.IsSuccessStatusCode) { // Pour ajouter les présences for (int i = 0; i < selectedAnime.Count(); i++) { Presences pre = new Presences(); pre.codeReunion = reunion.codeReunion; pre.useless = 1; pre.codeAnime = selectedAnime[i].codeAnime; string jsonPresence = JsonConvert.SerializeObject(pre); HttpContent contentPresence = new StringContent(jsonPresence, Encoding.UTF8, "application/json"); HttpResponseMessage responsefav = await client.PostAsync("http://scoutome.azurewebsites.net/api/presences", contentPresence); if (responsefav.IsSuccessStatusCode) { } } } return false; }
private static async Task AlbumsControllerTest(HttpClient client) { // create album await client.PostAsync("Albums/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 009") })); await client.PostAsync("Albums/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 010") })); // get all albums Console.WriteLine(await client.GetStringAsync("Albums/All")); // update album await client.PutAsync("Albums/Update", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("id", "2"), new KeyValuePair<string, string>("year", "2014"), new KeyValuePair<string, string>("producer", "gosho ot pochivka") })); // delete album await client.DeleteAsync("Albums/Delete/1"); // add song to album await client.PutAsync("Albums/AddSong?albumId=2&songId=2", null); // add artist to album await client.PutAsync("Albums/AddArtist?albumId=2&artistId=2", null); }
public static async Task<string> GetAccessToken(string username, string password) { try { var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip, AllowAutoRedirect = false }; using (var tempHttpClient = new HttpClient(handler)) { //Get session cookie var sessionResp = await tempHttpClient.GetAsync(Resources.PtcLoginUrl); var data = await sessionResp.Content.ReadAsStringAsync(); var lt = JsonHelper.GetValue(data, "lt"); var executionId = JsonHelper.GetValue(data, "execution"); //Login var loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("lt", lt), new KeyValuePair<string, string>("execution", executionId), new KeyValuePair<string, string>("_eventId", "submit"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password) })); var decoder = new WwwFormUrlDecoder(loginResp.Headers.Location.Query); var ticketId = decoder.GetFirstValueByName("ticket"); if (string.IsNullOrEmpty(ticketId)) throw new PtcOfflineException(); //Get tokenvar var tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("client_id", "mobile-app_pokemon-go"), new KeyValuePair<string, string>("redirect_uri", "https://www.nianticlabs.com/pokemongo/error"), new KeyValuePair<string, string>("client_secret", "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR"), new KeyValuePair<string, string>("grant_type", "refresh_token"), new KeyValuePair<string, string>("code", ticketId) })); var tokenData = await tokenResp.Content.ReadAsStringAsync(); decoder = new WwwFormUrlDecoder(tokenData); return decoder.GetFirstValueByName("access_token"); } } catch (Exception) { return string.Empty; } }
public static async Task<string> GetAccessToken(string username, string password) { var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip, AllowAutoRedirect = false }; using (var tempHttpClient = new HttpClient(handler)) { //Get session cookie var sessionResp = await tempHttpClient.GetAsync(Resources.PtcLoginUrl); var data = await sessionResp.Content.ReadAsStringAsync(); if (data == null) throw new PtcOfflineException(); if (sessionResp.StatusCode == HttpStatusCode.InternalServerError || data.Contains("<title>Maintenance")) throw new PtcOfflineException(); var lt = JsonHelper.GetValue(data, "lt"); var executionId = JsonHelper.GetValue(data, "execution"); //Login var loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("lt", lt), new KeyValuePair<string, string>("execution", executionId), new KeyValuePair<string, string>("_eventId", "submit"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password) })); if (loginResp.Headers.Location == null) throw new PtcOfflineException(); var ticketId = HttpUtility.ParseQueryString(loginResp.Headers.Location.Query)["ticket"]; if (ticketId == null) throw new PtcOfflineException(); //Get tokenvar var tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("client_id", "mobile-app_pokemon-go"), new KeyValuePair<string, string>("redirect_uri", "https://www.nianticlabs.com/pokemongo/error"), new KeyValuePair<string, string>("client_secret", "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR"), new KeyValuePair<string, string>("grant_type", "refresh_token"), new KeyValuePair<string, string>("code", ticketId) })); var tokenData = await tokenResp.Content.ReadAsStringAsync(); return HttpUtility.ParseQueryString(tokenData)["access_token"]; } }
async public Task WebClientServerTestAsync() { HttpConfiguration configuration = new HttpConfiguration(); HotsApi.Configure(configuration); using (HttpServer server = new HttpServer(configuration)) { using (HttpClient client = new HttpClient(server)) { client.BaseAddress = new Uri("http://host/api/"); string uri = "hero/"; HttpResponseMessage response = await client.GetAsync(uri); Assert.IsTrue(response.IsSuccessStatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseContent); // Get Hero Types uri = "herotype/"; response = await client.GetAsync(uri); Assert.IsTrue(response.IsSuccessStatusCode); responseContent = await response.Content.ReadAsStringAsync(); Dictionary<string, string> heroTypes = JsonConvert .DeserializeObject<IdName[]>(responseContent) .ToDictionary(kv => kv.Id, kv => kv.Name); Debug.WriteLine(responseContent); // Get Hero States uri = "herostate/"; response = await client.GetAsync(uri); Assert.IsTrue(response.IsSuccessStatusCode); responseContent = await response.Content.ReadAsStringAsync(); Dictionary<string, string> heroStates = JsonConvert .DeserializeObject<IdName[]>(responseContent) .ToDictionary(kv => kv.Id, kv => kv.Name); Debug.WriteLine(responseContent); // Create a Hero uri = $"hero?name=heroA&type={heroTypes.Keys.First()}&price=5"; StringContent requestContent = new StringContent(string.Empty, Encoding.UTF8, "application/json"); response = await client.PostAsync(uri, requestContent); Assert.IsTrue(response.IsSuccessStatusCode); responseContent = await response.Content.ReadAsStringAsync(); IdName hero = JsonConvert.DeserializeObject<IdName>(responseContent); Debug.WriteLine(responseContent); // Add A Free-To-Play period uri = $"freetoplayperiod?hero={hero.Id}&begin=2016%2F10%2F10&end=2016%2F10%2F17"; requestContent = new StringContent(string.Empty, Encoding.UTF8, "application/json"); response = await client.PostAsync(uri, requestContent); Assert.IsTrue(response.IsSuccessStatusCode); responseContent = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseContent); } } }
public async Task Reset() { using (var client = new HttpClient()) { var response = await client.PostAsync(_shoppingCartBaseUrl + "?reset=true",null); response.EnsureSuccessStatusCode(); response = await client.PostAsync(_ordersBaseUrl + "?reset=true", null); response.EnsureSuccessStatusCode(); } }
/// <summary> /// /// </summary> /// <param name="url"></param> /// <exception cref="UnauthorizedAccessException"></exception> /// <returns></returns> public async Task<ScannerProcess> CreateProcessAsync(string url) { if (this.Token == null) throw new UnauthorizedAccessException("Empty token!"); else this.Token.Validate(); using (HttpClient client = new HttpClient()) { client.SetCopyleaksClient(HttpContentTypes.Json, this.Token); CreateCommandRequest req = new CreateCommandRequest() { URL = url }; HttpResponseMessage msg; if (File.Exists(url)) { FileInfo localFile = new FileInfo(url); // Local file. Need to upload it to the server. using (var content = new MultipartFormDataContent("Upload----" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture))) { using (FileStream stream = File.OpenRead(url)) { content.Add(new StreamContent(stream, (int)stream.Length), "document", Path.GetFileName(url)); msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-file", content).Result; } } } else { // Internet path. Just submit it to the server. HttpContent content = new StringContent( JsonConvert.SerializeObject(req), Encoding.UTF8, HttpContentTypes.Json); msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-url", content).Result; } if (!msg.IsSuccessStatusCode) { var errorJson = await msg.Content.ReadAsStringAsync(); var errorObj = JsonConvert.DeserializeObject<BadResponse>(errorJson); if (errorObj == null) throw new CommandFailedException(msg.StatusCode); else throw new CommandFailedException(errorObj.Message, msg.StatusCode); } string json = await msg.Content.ReadAsStringAsync(); CreateResourceResponse response = JsonConvert.DeserializeObject<CreateResourceResponse>(json); return new ScannerProcess(this.Token, response.ProcessId); } }
static async Task chamarServio() { using (var RESTClient = new HttpClient()) { //RESTClient.BaseAddress = new Uri("http://localhost:2893/"); StringBuilder novoProposta = new StringBuilder(); novoProposta.Append("<Proposta xmlns=\"http://sclovers.com/Proposta\">"); novoProposta.Append("<NomeCliente>Maria</NomeCliente>"); novoProposta.Append("<DescricaoProposta>Minha proposta é R$ 15,00</DescricaoProposta>"); novoProposta.Append("<DataHoraEnviada>2014-10-30</DataHoraEnviada>"); novoProposta.Append("</Proposta>"); HttpResponseMessage respPOST = await RESTClient.PostAsync( new Uri("http://localhost:2893/Proposta.svc/enviarProposta"), new StringContent(novoProposta.ToString(), Encoding.UTF8, "application/xml")); Console.WriteLine(respPOST.StatusCode); novoProposta.Clear(); novoProposta.Append("<Proposta xmlns=\"http://sclovers.com/Proposta\">"); novoProposta.Append("<NomeCliente>João</NomeCliente>"); novoProposta.Append("<DescricaoProposta>Minha proposta é R$ 15,00</DescricaoProposta>"); novoProposta.Append("<DataHoraEnviada>2014-10-30</DataHoraEnviada>"); novoProposta.Append("</Proposta>"); respPOST = await RESTClient.PostAsync( new Uri("http://localhost:2893/Proposta.svc/enviarProposta"), new StringContent(novoProposta.ToString(), Encoding.UTF8, "application/xml")); Console.WriteLine(respPOST.StatusCode); HttpResponseMessage resp = await RESTClient.GetAsync(new Uri("http://localhost:2893/Proposta.svc/listaPropostaJson")); if (resp.IsSuccessStatusCode) { Stream stream; stream = await resp.Content.ReadAsStreamAsync(); DataContractJsonSerializer dataJson = new DataContractJsonSerializer(typeof(Proposta[])); Proposta[] propostas = (Proposta[])dataJson.ReadObject(stream); foreach (Proposta item in propostas) { Console.WriteLine("Id: {0}", item.Id); Console.WriteLine("Nome: {0}", item.NomeCliente); Console.WriteLine("Proposta: {0}", item.DescricaoProposta); Console.WriteLine("Data: {0}", item.DataHoraEnviada); } } Console.WriteLine(resp.StatusCode); } }
private static async Task RunClientServerSample(Uri server) { using(var httpClient = new HttpClient()) { { var result = await httpClient.PostAsync($"{server}CreateArticle.command", new StringContent(@"{ ""CQRSMicroservices.Articles.CreateArticleCommand"" : { ""ArticleId"": ""d0174342-71b0-4deb-b5b8-d1064d07ec3c"", ""Description"": ""iPhone 6S 64 GB Space Gray"", ""Price"": 850.99, } }")); var resultContent = await result.Content.ReadAsStringAsync(); System.Console.WriteLine(resultContent); } { var result = await httpClient.PostAsync($"{server}CreateCustomer.command", new StringContent(@"{ ""CQRSMicroservices.Customers.CreateCustomerCommand"" : { ""CustomerId"": ""14b2e8ec-31e2-4a19-b40a-6f77ae3cf4f0"", ""Name"": ""AFAS Software"" } }")); var resultContent = await result.Content.ReadAsStringAsync(); System.Console.WriteLine(resultContent); } { var result = await httpClient.PostAsync($"{server}SellArticle.command", new StringContent(@"{ ""CQRSMicroservices.Articles.SellArticleCommand"" : { ""ArticleId"": ""d0174342-71b0-4deb-b5b8-d1064d07ec3c"", ""CustomerId"": ""14b2e8ec-31e2-4a19-b40a-6f77ae3cf4f0"" } }")); var resultContent = await result.Content.ReadAsStringAsync(); System.Console.WriteLine(resultContent); } System.Console.WriteLine("Wait a second or two to let the QueryModelBuilder catch up..."); await Task.Delay(2000); { var result = await httpClient.GetAsync($"{server}CQRSMicroservices/Articles/GetArticleQuery.query?ArticleId=d0174342-71b0-4deb-b5b8-d1064d07ec3c"); var document = await result.Content.ReadAsStringAsync(); System.Console.WriteLine(document); } System.Console.ReadKey(); } }
public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) { var url = activityContext.GetState<string>("Url"); var verb = (activityContext.GetState<string>("Verb") ?? "GET").ToUpper(); var headers = activityContext.GetState<string>("Headers"); var formValues = activityContext.GetState<string>("FormValues") ?? ""; using (var httpClient = new HttpClient {BaseAddress = new Uri(url)}) { HttpResponseMessage response; httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!String.IsNullOrWhiteSpace(headers)) { foreach (var header in ParseKeyValueString(headers)) { httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } } switch (verb) { default: case "GET": response = httpClient.GetAsync("").Result; break; case "POST": var format = activityContext.GetState<string>("FormFormat"); switch (format) { default: case "KeyValue": var form = ParseKeyValueString(formValues); response = httpClient.PostAsync("", new FormUrlEncodedContent(form)).Result; break; case "Json": var json = formValues.Replace("((", "{").Replace("))", "}"); response = httpClient.PostAsync("", new StringContent(json, Encoding.UTF8, "application/json")).Result; break; } break; } workflowContext.SetState("WebRequestResponse", response.Content.ReadAsStringAsync().Result); if (response.IsSuccessStatusCode) yield return T("Success"); else yield return T("Error"); } }
public void FakeServer_CapturesAllRequests() { using (var fakeServer = new FakeServer()) { fakeServer.Start(); var baseAddress = fakeServer.BaseUri; Action<Action, int> repeat = (a, times) => { for (var i = 0; i < times; i++) a(); }; var url1 = "/request1"; var url2 = "/request2"; var url3 = "/request3"; var url4 = "/request4"; var httpClient = new HttpClient(); httpClient.DeleteAsync(new Uri(baseAddress + url1)).Wait(); repeat(() => httpClient.GetAsync(new Uri(baseAddress + url2)).Wait(), 2); repeat(() => httpClient.PostAsync(new Uri(baseAddress + url3), new StringContent(url3)).Wait(), 3); repeat(() => httpClient.PutAsync(new Uri(baseAddress + url4), new StringContent(url4)).Wait(), 4); fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1); fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2); fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3); fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4); } }
static void Main(string[] args) { Console.WriteLine("Username:"******"Password:"******"http://localhost:3915/Account/Login"; var client = new HttpClient(); var response = client.PostAsync(uri, new User() { Username = username, Password = password }, new JsonMediaTypeFormatter()).Result; IEnumerable<string> values; response.Headers.TryGetValues("Set-Cookie", out values); if (null == values || string.IsNullOrEmpty(values.First())) { Console.WriteLine("Invalid Username or password;"); } else { string newUri = "http://localhost:3915/customer/get/1"; string cookie = values.First(); client.DefaultRequestHeaders.Add("Cookie", cookie); var getRequestResponse = client.GetAsync(newUri).Result; Customer customer = getRequestResponse.Content.ReadAsAsync<Customer>().Result; Console.WriteLine("Customer Id: {0}; Name: {1}", customer.Id, customer.Name); } Console.ReadLine(); }
/// <summary> /// Does setup of AutoCAD IO. /// This method will need to be invoked once before any other methods of this /// utility class can be invoked. /// </summary> /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param> /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param> public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret) { try { String clientId = autocadioclientid; String clientSecret = autocadioclientsecret; Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/"); container = new AIO.Operations.Container(uri); container.Format.UseJson(); using (var client = new HttpClient()) { var values = new List<KeyValuePair<string, string>>(); values.Add(new KeyValuePair<string, string>("client_id", clientId)); values.Add(new KeyValuePair<string, string>("client_secret", clientSecret)); values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials")); var requestContent = new FormUrlEncodedContent(values); var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result; var responseContent = response.Content.ReadAsStringAsync().Result; var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent); _accessToken = resValues["token_type"] + " " + resValues["access_token"]; if (!string.IsNullOrEmpty(_accessToken)) { container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken); } } } catch (System.Exception ex) { Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message)); container = null; throw; } }
private async void AppBarButton_Click(object sender, RoutedEventArgs e) { HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(ip); models.Autenticacao a = new models.Autenticacao { Login = login.Text, Senha = senha.Text }; string s = "=" + JsonConvert.SerializeObject(a); var content = new StringContent(s, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync("/api/user/login", content); var str = response.Content.ReadAsStringAsync().Result; str = "OK"; if (str == "OK") { this.Frame.Navigate(typeof(MainPage)); } }
HttpAbfrage(String Ziel, HttpContent content) { //################################################################################################ var httpClient = new HttpClient(); // Neue httpClient instanz //################################################################################################## // mit Cockies aber nicht zu ende Programmiert weil wir keine Cockies nutzen CookieContainer cookie = new CookieContainer(); // Cockie Container Construcktor HttpClientHandler handler = new HttpClientHandler() // nutze beim zugriff cockies { }; HttpClient client = new HttpClient(handler as HttpMessageHandler) // neuer http client { BaseAddress = new Uri(GlobalData.Uri2 + Ziel + GlobalData.SessionID) // hier wird auch gleich die Session an das ziel angehangen // url aus uri 2 nutzen test2.php }; handler.UseCookies = false; // beim zugriff cockies nicht zulassen handler.UseDefaultCredentials = false; //################################################################################################# // Jetzt mit POST // Schritt 4 Abfrage abschicken und ergebnis entgegennehmen HttpResponseMessage response = await httpClient.PostAsync(client.BaseAddress, content); // schicke die abfrage an die Url , dann warte bis antwort komplett und speicher erst mal alles GlobalData.HttpResponse = await response.Content.ReadAsStringAsync(); // MessageDialog msgboxRespons = new MessageDialog(GlobalData.HttpResponse); // await msgboxRespons.ShowAsync(); // Zeige mir an was angekommen ist return GlobalData.HttpResponse; }
/// <summary> /// Post request /// </summary> /// <param name="uri">Enqueue endpoint URI</param> /// <param name="authenticationHeader">Authentication header</param> /// <param name="bodyStream">Body stream</param> /// <param name="message">ActivityMessage context</param> /// <returns></returns> public async Task<HttpResponseMessage> SendPostRequestAsync(Uri uri, Stream bodyStream, string externalCorrelationHeaderValue = null) { using (HttpClientHandler handler = new HttpClientHandler() { UseCookies = false }) { using (HttpClient httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.Authorization = AuthenticationHelper.GetValidAuthenticationHeader(); // Add external correlation id header id specified and valid if (!string.IsNullOrEmpty(externalCorrelationHeaderValue)) { httpClient.DefaultRequestHeaders.Add(Program.ExternalCorrelationHeader, externalCorrelationHeaderValue); } if (bodyStream != null) { using (StreamContent content = new StreamContent(bodyStream)) { return await httpClient.PostAsync(uri, content); } } } } return new HttpResponseMessage() { Content = new StringContent("Request failed at client.", Encoding.ASCII), StatusCode = System.Net.HttpStatusCode.PreconditionFailed }; }
/// <summary> /// 提交被扫支付API /// http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=5_5 /// 1.应用场景:收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台,由商户收银台或者商户后台调用该接口发起支付。 ///是否需要证书:不需要。 /// <param name="appid">(必填) String(32) 微信分配的公众账号ID</param> /// <param name="mch_id">(必填) String(32) 微信支付分配的商户号</param> /// <param name="device_info"> String(32) 微信支付分配的终端设备号,商户自定义</param> /// <param name="nonce_str">(必填) String(32) 随机字符串,不长于32位</param> /// <param name="body">(必填) String(32) 商品描述 商品或支付单简要描</param> /// <param name="detail"> String(8192) 商品详情 商品名称明细列表</param> /// <param name="attach"> String(127) 附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据</param> /// <param name="out_trade_no">(必填) String(32) 商家订单ID,32个字符内、可包含字母, 其他说明见第4.2节商户订单号:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_2 </param> /// <param name="fee_type">符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见第4.2节货币类型: http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_2 </param> /// <param name="total_fee">(必填) Int 订单总金额,只能为整数,详见第4.2节支付金额:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_2 </param> /// <param name="spbill_create_ip">(必填) String(32)终端IP APP和网页支付提交用户端IP,Native支付填调用微信支付API的机器IP。</param> /// <param name="time_start">String(14) 订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。</param> /// <param name="time_expire">String(14) 订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。</param> /// <param name="goods_tag">String(32) 商品标记,代金券或立减优惠功能的参数,说明详见第10节代金券或立减优惠:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=10_1 </param> /// <param name="auth_code">String(128) 授权码 扫码支付授权码,设备读取用户微信中的条码或者二维码信息 </param> /// <param name="partnerKey">API密钥</param> /// <returns>返回json字符串,格式参见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=5_5 </returns> public static dynamic Submit(string appid, string mch_id, string device_info, string nonce_str, string body, string detail, string attach, string out_trade_no, string fee_type, int total_fee, string spbill_create_ip, string time_start, string time_expire, string goods_tag, string auth_code, string partnerKey) { var stringADict = new Dictionary<string, string>(); stringADict.Add("appid", appid); stringADict.Add("mch_id", mch_id); stringADict.Add("device_info", device_info); stringADict.Add("nonce_str", nonce_str); stringADict.Add("body", body); stringADict.Add("attach", attach); stringADict.Add("out_trade_no", out_trade_no); stringADict.Add("fee_type", fee_type); stringADict.Add("total_fee", total_fee.ToString()); stringADict.Add("spbill_create_ip", spbill_create_ip); stringADict.Add("time_start", time_start); stringADict.Add("time_expire", time_expire); stringADict.Add("goods_tag", goods_tag); stringADict.Add("auth_code", auth_code); var sign = WxPayAPI.Sign(stringADict, partnerKey);//生成签名字符串 var postdata = PayUtil.GeneralPostdata(stringADict, sign); var url = "https://api.mch.weixin.qq.com/pay/micropay"; var client = new HttpClient(); var result = client.PostAsync(url, new StringContent(postdata)).Result; if (!result.IsSuccessStatusCode) return string.Empty; return new DynamicXml(result.Content.ReadAsStringAsync().Result); }
public async Task<string> CreateScheduleAsync(object attrs) { var url = BaseUrl + "/schedules"; var bodyJson = JsonConvert.SerializeObject(attrs); try { HttpClient client = new HttpClient(); HttpResponseMessage resp = await client.PostAsync(url, new StringContent(bodyJson)); resp.EnsureSuccessStatusCode(); var result = await resp.Content.ReadAsStringAsync(); Debug.WriteLine(result); if (!result.Contains("success")) { return null; } JArray resultArray = JArray.Parse(result); JObject idObject = (JObject)resultArray[0]; string scheduleId = idObject["success"]["id"].ToString(); return scheduleId; } catch (Exception ex) { Debug.WriteLine(ex); return null; } }
public double GET(string uid) { bool t = true; double unique; do { var client = new HttpClient(); client.BaseAddress = new Uri("http://api.text.ru"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("uid", uid), new KeyValuePair<string, string>("userkey", Key), }); var result = client.PostAsync("/post", content).Result; string resultContent = result.Content.ReadAsStringAsync().Result; var res = JsonConvert.DeserializeObject<Plagiarism>(resultContent); unique = res.uniq; int error = res.err; if (error == 181) { t = false; Thread.Sleep(10000); } else t = true; } while (!t); Repository.Work.Plag = unique; return unique; }
public void Authenticate() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(webServiceRootPath); var content = new StringContent( string.Format("grant_type=password&username={0}&password={1}", login.Replace("@", "%40"), password), Encoding.UTF8, "text/plain"); client.Timeout = TimeSpan.FromSeconds(30); var response = client.PostAsync("Token", content).Result; if (!response.IsSuccessStatusCode) { throw new Exception("Authentication failed " + FormatHttpError(response)); } string serialized = response.Content.ReadAsStringAsync().Result; var model = JsonConvert.DeserializeObject<TokenResponseModel>(serialized); if (!"bearer".Equals(model.TokenType, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Returned token is not of bearer type, actual: " + model.TokenType); } token = model.AccessToken; } }
public static async Task<bool> TryHitMetricsEndPoint(JObject jObject) { try { using (var httpClient = new System.Net.Http.HttpClient()) { var response = await httpClient.PostAsync(new Uri(MetricsServiceUri + MetricsDownloadEventMethod), new StringContent(jObject.ToString(), Encoding.UTF8, ContentTypeJson)); //print the header Console.WriteLine("HTTP status code : {0}", response.StatusCode); if (response.StatusCode == HttpStatusCode.Accepted) { return true; } else { return false; } } } catch (HttpRequestException hre) { Console.WriteLine("Exception : {0}", hre.Message); return false; } }
public async Task<String> PostStringAsync(Uri uri, IDictionary<String, String> content) { using (var http = new HttpClient()) { var formContent = new FormUrlEncodedContent(content); var response = await http.PostAsync(uri, formContent); return await response.Content.ReadAsStringAsync(); } }
public override async Task<string> GetTokenFromGrant(string grant) { string token = ""; using (var client = new HttpClient()) { Dictionary<string, string> postvalues = new Dictionary<string, string> { { "code", grant }, { "client_id", AppID }, { "client_secret", AppSecret }, { "redirect_uri", RedirectURI }, { "grant_type", "authorization_code" } }; var content = new FormUrlEncodedContent(postvalues); var response = await client.PostAsync("https://www.googleapis.com/oauth2/v4/token", content); var responseString = await response.Content.ReadAsStringAsync(); Dictionary<string, string> responseJSON = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString); token = responseJSON["access_token"]; } return token; }
private HashResponseContent InternalRequestHashes(HashRequestContent request) { using (var client = new System.Net.Http.HttpClient()) { client.BaseAddress = _baseAddress; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-AuthToken", this.apiKey); var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = client.PostAsync(_endpoint, content).Result; switch (response.StatusCode) { case HttpStatusCode.OK: //200 AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(Convert.ToUInt32(((String[])response.Headers.GetValues("X-AuthTokenExpiration"))[0])).ToLocalTime(); MaxRequestCount = Convert.ToUInt16(((string[])response.Headers.GetValues("X-MaxRequestCount"))[0]); RatePeriodEnd = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(Convert.ToUInt32(((String[])response.Headers.GetValues("X-RatePeriodEnd"))[0])).ToLocalTime(); RateRequestRemaining = Convert.ToUInt16(((string[])response.Headers.GetValues("X-RateRequestsRemaining"))[0]); RateLimitSeconds = Convert.ToUInt16(((string[])response.Headers.GetValues("X-RateLimitSeconds"))[0]); var remainingSeconds = (DateTime.Now - RatePeriodEnd).TotalSeconds * -1; Logger.Debug($"{RateRequestRemaining}/{MaxRequestCount} requests remaining for the next {remainingSeconds} seconds. Key expires on: {AuthTokenExpiration}"); if ((AuthTokenExpiration - DateTime.Now).TotalDays <= 3) { if (ExpirationCounter-- == 0) { ExpirationCounter = 1000; Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Attention! Your key is expiring in {(AuthTokenExpiration - DateTime.Now).Days} days and {(AuthTokenExpiration - DateTime.Now).Hours} hours! Expiration date: {AuthTokenExpiration}", LogLevel.Warning); } } ; return(JsonConvert.DeserializeObject <HashResponseContent>(response.Content.ReadAsStringAsync().Result)); case HttpStatusCode.BadRequest: // 400 var responseText = response.Content.ReadAsStringAsync().Result; throw new HasherException($"[HashService] 400: Your key is probably expired! {responseText}"); case HttpStatusCode.Unauthorized: // 401 Shared.KeyCollection.removeKey(this.apiKey); throw new HasherException("[HashService] 401: Your PF-Hashkey you provided is incorrect (or not valid anymore). "); case (HttpStatusCode)429: // To many requests responseText = response.Content.ReadAsStringAsync().Result; throw new HasherException($"[HashService] 429: Your request has been limited (Message : {responseText})"); case HttpStatusCode.ServiceUnavailable: responseText = response.Content.ReadAsStringAsync().Result; throw new HasherException($"[HashService] 503: It seems PokeFarmer server {_baseAddress}{_endpoint} is unavailable (Message : {responseText}) "); default: RandomHelper.RandomSleep(10000, 11000); throw new HasherException($"[HashService] Unknown: Pokefamer Hash API ({_baseAddress}{_endpoint}) might down!"); } } }
private async static Task <List <CitrixApplicationInfo> > GetResourcesFromStoreFront(string SFURL, CitrixAuthCredential Creds, bool UseSSL) { List <CitrixApplicationInfo> _applicationList = new List <CitrixApplicationInfo>(); CookieContainer _cookieContainer = new CookieContainer(); Cookie _aspnetSessionIdCookie = new Cookie("ASP.NET_SessionId", Creds.SessionID, Creds.CookiePath, Creds.CookieHost); Cookie _csrfTokenCookie = new Cookie("CsrfToken", Creds.CSRFToken, Creds.CookiePath, Creds.CookieHost); Cookie _authIDCookie = new Cookie("CtxsAuthId", Creds.AuthToken, Creds.CookiePath, Creds.CookieHost); _cookieContainer.Add(_aspnetSessionIdCookie); _cookieContainer.Add(_csrfTokenCookie); _cookieContainer.Add(_authIDCookie); HttpClientHandler _clientHandler = new HttpClientHandler(); _clientHandler.CookieContainer = _cookieContainer; System.Net.Http.HttpClient _client = new System.Net.Http.HttpClient(_clientHandler); _client.BaseAddress = new Uri(SFURL); string _postResourceUrl = (SFURL.EndsWith("/")) ? "Resources/List" : "/Resources/List"; string _resourcesURL = SFURL + _postResourceUrl; if (UseSSL) { _client.DefaultRequestHeaders.Add("X-Citrix-IsUsingHTTPS", "Yes"); } else { _client.DefaultRequestHeaders.Add("X-Citrix-IsUsingHTTPS", "No"); } _client.DefaultRequestHeaders.Add("Csrf-Token", Creds.CSRFToken); _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); StringContent _bodyContent = new StringContent(""); HttpResponseMessage _listResourcesResp = await _client.PostAsync(_resourcesURL, _bodyContent); if (_listResourcesResp.StatusCode == HttpStatusCode.OK) { string _resourcesJSON = await _listResourcesResp.Content.ReadAsStringAsync(); JObject _resourcesBase = JObject.Parse(_resourcesJSON); _applicationList = Newtonsoft.Json.JsonConvert.DeserializeObject <List <CitrixApplicationInfo> >(_resourcesBase["resources"].ToString()); foreach (var _resource in _applicationList) { _resource.Auth = Creds; //_resource.StorefrontURL; } } return(_applicationList); }
private async void ButtonReg_Click(object sender, RoutedEventArgs e) { if (userBox.Text == "" || passwordBox.Password.ToString() == "") { await new MessageDialog("Username & Password are required!").ShowAsync(); return; } var user = new User { Username = userBox.Text, Password = passwordBox.Password.ToString() }; using (var client = new System.Net.Http.HttpClient()) { var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); var result = client.PostAsync($"{App.BaseUri}/register", content).Result; if (result.IsSuccessStatusCode == true) { var a = result.Content.ReadAsStringAsync().Result; if (a == "\"exist\"") { await new MessageDialog("The usename is exist, try another user name").ShowAsync(); } else { await new MessageDialog("Success! :)").ShowAsync(); var currentUser = JsonConvert.DeserializeObject <User>(a); App.CurrentUser = currentUser; Dictionary <string, string> userDetails = new Dictionary <string, string>(); userDetails.Add("userName", App.CurrentUser.Username); myApp.MyHubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(SERVER_URL, userDetails); myApp.MyHubProxy = myApp.MyHubConnection.CreateHubProxy("ChatHub"); if (myApp.MyHubConnection.State != Microsoft.AspNet.SignalR.Client.ConnectionState.Connected) { try { await myApp.MyHubConnection.Start(); } catch { await new MessageDialog($"Can't connect to server {myApp.MyHubConnection.Url}").ShowAsync(); return; } } Frame.Navigate(typeof(Lobby)); } } else { await new MessageDialog("Can't connect to server").ShowAsync(); return; } } }
async public Task <CookieContainer> getAccountCookie(string mail, string pass) { if (mail == null || pass == null) { return(null); } var isNew = true; string loginUrl; Dictionary <string, string> param; if (isNew) { loginUrl = "https://account.nicovideo.jp/login/redirector"; param = new Dictionary <string, string> { { "mail_tel", mail }, { "password", pass }, { "auth_id", "15263781" } //dummy }; } else { loginUrl = "https://secure.nicovideo.jp/secure/login?site=nicolive"; param = new Dictionary <string, string> { { "mail", mail }, { "password", pass } }; } try { var handler = new System.Net.Http.HttpClientHandler(); handler.UseCookies = true; var http = new System.Net.Http.HttpClient(handler); var content = new System.Net.Http.FormUrlEncodedContent(param); var _res = await http.PostAsync(loginUrl, content); var res = await _res.Content.ReadAsStringAsync(); // var a = _res.Headers; // if (res.IndexOf("login_status = 'login'") < 0) return null; var cc = handler.CookieContainer; var c = cc.GetCookies(TargetUrl)["user_session"]; var secureC = cc.GetCookies(TargetUrl)["user_session_secure"]; //cc = copyUserSession(cc, c, secureC); log += (c == null) ? "ユーザーセッションが見つかりませんでした。" : "ユーザーセッションが見つかりました。"; log += (secureC == null) ? "secureユーザーセッションが見つかりませんでした。" : "secureユーザーセッションが見つかりました。"; if (c == null && secureC == null) { return(null); } return(cc); } catch (Exception e) { util.debugWriteLine(e.Message + e.StackTrace); return(null); } }
private void BtnSubmit_Clicked(object sender, EventArgs e) { using (var client = new System.Net.Http.HttpClient()) { var scoreRequest = new { Inputs = new Dictionary <string, List <Dictionary <string, string> > >() { { "input1", new List <Dictionary <string, string> >() { new Dictionary <string, string>() { { "Class", "1" }, { "sepal-length", entSepalLength.Text }, { "sepal-width", entSepalWidth.Text }, { "petal-length", entPetalLength.Text }, { "petal-width", entPetalWidth.Text }, } } }, }, GlobalParameters = new Dictionary <string, string>() { } }; const string apiKey = "FYT7/RTnqbT/6i9TGNKGQQCiYNowmIK9ACpNuMMEcJzxzmo2aVcGKGQSbExJN5Ub0G416as6nNk9yUCnjb121A=="; // Replace this with the API key for the web service client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/2184572330564902bdafc6ff5145c22f/services/4595c4c853c74f14bbaa69c46c928a26/execute?api-version=2.0&format=swagger"); var json = JsonConvert.SerializeObject(scoreRequest); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync("", content).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; var jsonResult = JsonConvert.DeserializeObject <MyModel>(result); entScoredLabel.Text = jsonResult.Results.output1[0].ScoredLabels; entScoredProb.Text = jsonResult.Results.output1[0].ScoredProbabilities; } else { DisplayAlert("Keterangan", "Gagal akses web services", "OK"); } } }
public async Task <ActionResult> UploadDocument(IEnumerable <HttpPostedFileBase> files, string comments, Guid requestID, Guid?taskID, string authToken, DTO.Enums.TaskItemTypes?taskItemType) { List <Lpp.Dns.DTO.ExtendedDocumentDTO> documents = new List <Lpp.Dns.DTO.ExtendedDocumentDTO>(); using (var web = new System.Net.Http.HttpClient()) { web.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken); web.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data")); HttpResponseMessage response = new HttpResponseMessage(); foreach (var f in files) { var file = f; using (MultipartFormDataContent container = new MultipartFormDataContent()) { string filename = System.IO.Path.GetFileName(file.FileName); container.Add(new StreamContent(file.InputStream), "files", filename); container.Add(new StringContent(System.IO.Path.GetFileNameWithoutExtension(filename)), "documentName"); container.Add(new StringContent(requestID.ToString()), "requestID"); if (taskID.HasValue) { container.Add(new StringContent(taskID.Value.ToString()), "taskID"); if (taskItemType.HasValue) { container.Add(new StringContent(taskItemType.Value.ToString("D")), "taskItemType"); } } if (!string.IsNullOrWhiteSpace(comments)) { container.Add(new StringContent(comments), "comments"); } response = await web.PostAsync(WebConfigurationManager.AppSettings["ServiceUrl"] + "/documents/upload", container); string body = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { Lpp.Utilities.BaseResponse <DTO.ExtendedDocumentDTO> savedDocument = Newtonsoft.Json.JsonConvert.DeserializeObject <Lpp.Utilities.BaseResponse <DTO.ExtendedDocumentDTO> >(body); if (savedDocument.results != null && savedDocument.results.Length > 0) { documents.AddRange(savedDocument.results); } } else { Response.StatusCode = (int)response.StatusCode; return(Json(new { success = false, content = body }, "text/plain")); } } } } return(Json(new { success = true, content = Newtonsoft.Json.JsonConvert.SerializeObject(documents) }, "text/plain")); }
public static async Task <T> PostAsync <T>(this System.Net.Http.HttpClient httpClient, string url, object data) { var responseMessage = await httpClient.PostAsync(url, data); responseMessage.EnsureSuccessStatusCode(); var result = await responseMessage.Content.ReadAsync <T>(); return(result); }
public static async Task <HttpResponseMessage> PostButtonData(string json) { using (var client = new System.Net.Http.HttpClient()) { var content = new StringContent(json, Encoding.UTF8, "application/json"); return(await client.PostAsync(App.MainUrl, content)); } }
public async Task <T> PostAsync <T>(Uri url, object body) { var response = await _htppClient.PostAsync(url, new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); var strRes = await response.Content.ReadAsStringAsync(); return(JsonSerializer.Deserialize <T>(strRes)); }
/// <summary> /// Test Method and not to be used. /// </summary> /// <param name="item"></param> public static async void SetKegSettings(this KegConfig item) { var client = new System.Net.Http.HttpClient(); string url = $"{UrlCombine(Constants.COSMOSAzureFunctionsURL, "kegconfig")}?code={Constants.AF_KEGKEY}"; StringContent content = new StringContent(JsonConvert.SerializeObject(item)); var response = await client.PostAsync(url, content); var body = await response.Content.ReadAsStringAsync(); }
/// <summary> /// Adds a day of trip to the database when button clicked. /// </summary> public async void AddDay_Click() { if (SelectedTrip == null) { var dialog = new MessageDialog("You must choose a trip from the dropdown"); dialog.Commands.Add(new UICommand("Ok") { Id = 0 }); dialog.CancelCommandIndex = 0; var result = await dialog.ShowAsync(); return; } TripId = await GetId(); if (Day == 0 || City == null || Hotel == null || Dinner == null || Info == null || City == "" || Hotel == "" || Dinner == "" || Info == "") { var dialog = new MessageDialog("You must fill all fields"); dialog.Commands.Add(new UICommand("Ok") { Id = 0 }); dialog.CancelCommandIndex = 0; var result = await dialog.ShowAsync(); return; } var day = new DayOfTrip { Day = Day, City = City, Hotel = Hotel, Dinner = Dinner, MoneySpent = Money, AdditionalInfo = Info, TripId = TripId }; using (var client = new System.Net.Http.HttpClient()) { client.BaseAddress = new Uri(@"http://localhost:10051/api/"); var content = JsonConvert.SerializeObject(day); var httpContent = new StringContent(content, Encoding.UTF8, "application/json"); var json = await client.PostAsync("dayoftrips", httpContent); var nav = WindowWrapper.Current().NavigationServices.FirstOrDefault(); nav.Navigate(typeof(Views.GetTripPage)); } }
public async Task <string> SendRaw(string uri, byte[] json) { System.Net.Http.HttpClient http = new System.Net.Http.HttpClient(); var content = new ByteArrayContent(json); var response = await http.PostAsync(Host + uri, content); return(await response.Content.ReadAsStringAsync()); }
public static Task <HttpResponseMessage> PostAsJsonAsync <T>( this System.Net.Http.HttpClient httpClient, string url, T data) { var dataAsString = JsonConvert.SerializeObject(data); var content = new StringContent(dataAsString); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return(httpClient.PostAsync(url, content)); }
public async Task <JsonDefaultResponse <T> > Post <T>(string endpoint, object content) { StringContent stringContent = new StringContent(JsonTransformer.Serialize(content), Encoding.UTF8, "application/json"); HttpResponseMessage request = await client.PostAsync(endpoint, stringContent); string response = request.Content.ReadAsStringAsync().Result; return(JsonTransformer.Deserialize <JsonDefaultResponse <T> >(response)); }
public async Task <HttpResponseMessage> PostDataAsync(object data, string endPoint) { var jsonString = JsonConvert.SerializeObject(data); var postContent = new StringContent(jsonString, _defaultEncoding, _postContentType); var response = await _client.PostAsync(endPoint, postContent); return(response); }
/// <summary> /// read method post request /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public static async Task <string> ReadPostRequestAsync(string url, string data = null) { using (var client = new System.Net.Http.HttpClient()) { var response = await client.PostAsync(url, new StringContent(data, Encoding.UTF8, "application/json")); return(await response.Content.ReadAsStringAsync()); } }
internal async void GetPatientInfo(string value) { PatientName = value; var temp = new List <string>(); if (CrossConnectivity.Current.IsConnected == true) { try { HttpClient httpClient = new System.Net.Http.HttpClient(); dynamic p = new JObject(); p.Patient_Name = value; p.Site_Code = Library.KEY_USER_SiteCode; string stringPayload = JsonConvert.SerializeObject(p); var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(Library.URL + "/Searchpatient", httpContent); // HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Library.URL + "/Searchpatient/" + value + "/" + Library.KEY_USER_SiteCode); // HttpResponseMessage response = await httpClient.SendAsync(request); var data = await response.Content.ReadAsStringAsync(); var namelist = JsonConvert.DeserializeObject <ObservableCollection <dynamic> >(data); foreach (var item in namelist) { string name = item.Patient_Name; temp.Add(name); } PatientDatas = new List <string>(temp); if (!PatientDatas.Any()) { PatientDatas = new List <string> { "No Results" } } ; } catch (Exception) { } } else { var data = _patientRepo.QueryTable().Where(x => x.Patientname.ToLower().Contains(value.ToLower())); foreach (var item in data) { PatientDatas.Add(item.Patientname); } } }
private async Task <bool> PostProductsForPackageAsync(List <Products> products, int packageID) { HttpClient client = new System.Net.Http.HttpClient(); // Get All ProductsSuppliers into List List <ProductsSuppliers> prodsSuppsListFull; HttpResponseMessage response = await client.GetAsync("https://localhost:44327/api/ProductsSuppliersAPI"); prodsSuppsListFull = JsonConvert.DeserializeObject <List <ProductsSuppliers> >(await response.Content.ReadAsStringAsync()); // Get all ProductsSuppliers Id's for products in the list List <int> inputProductIds = new List <int>(); foreach (var item in products) { inputProductIds.Add(item.ProductId); } // Filter ProductsSuppliers List for only products that are in input products var PerProductSupplier = new List <ProductsSuppliers>(); List <ProductsSuppliers> prodsSuppsListFiltered = new List <ProductsSuppliers>(); // Assign the first ProductSupplierId to the Product which package uses foreach (int productid in inputProductIds) { prodsSuppsListFiltered.Add(prodsSuppsListFull.Find(ps => ps.ProductId == productid)); } // Got filtered list of productSupplierIds, now post this list 1 by 1 to Packages_Products_Suppliers List <HttpStatusCode> codes = new List <HttpStatusCode>(); foreach (var productSupplier in prodsSuppsListFiltered) { var newPackageProductSupplier = new PackagesProductsSuppliers { PackageId = packageID, ProductSupplierId = productSupplier.ProductSupplierId }; var content = JsonConvert.SerializeObject(newPackageProductSupplier); var httpContent = new StringContent(content, Encoding.UTF8, "application/json"); HttpResponseMessage responseFromPost = await client.PostAsync("https://localhost:44327/api/PackagesProductsSuppliersAPI", httpContent); codes.Add(responseFromPost.StatusCode); } // return true if all status codes are OK otherwise return false bool IsGoodRequest = true; foreach (HttpStatusCode code in codes) { if (code != HttpStatusCode.Created) { IsGoodRequest = false; } } return(IsGoodRequest); }
public static async Task <JsonValue> POSTreq(ServiceTypes services, T saleEntity) { Uri requestUri = new Uri(SaleItemGlobal.serviceURL + services); string json = Newtonsoft.Json.JsonConvert.SerializeObject(saleEntity); var objClint = new System.Net.Http.HttpClient(); HttpResponseMessage respon = objClint.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result; string responJsonText = await respon.Content.ReadAsStringAsync(); return(await Task.Run(() => JsonObject.Parse(responJsonText))); }
private async void button1_Click(object sender, RoutedEventArgs e) { Uri requestUri = new Uri("http://10.0.0.50:8080/api/stop"); //replace your Url var objClint = new System.Net.Http.HttpClient(); objClint.DefaultRequestHeaders.Add("key", "89034h8973hg83hg387g3hg0837h0g3hg08w34ashga34"); System.Net.Http.HttpResponseMessage respon = await objClint.PostAsync(requestUri, new StringContent("Test")); string responJsonText = await respon.Content.ReadAsStringAsync(); }
async Task serviceHilfe(IDialogContext context) { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); HttpContent content = new StringContent("Ticket 0038052: Netzwerkdrucker liefert Fehlercode."); await client.PostAsync("https://prod-13.northeurope.logic.azure.com:443/workflows/a0323b2e06fe49ce96d66677c53f1402/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=nWmc56Qfr7C8jx2_3mrRNm_sk_3K8ww2srrsoFVrNE4", content); await context.PostAsync("Das Problem wird an einen unserer freundlichen Support-Mitarbeiter weitergeleitet :)"); context.Wait(MessageReceived); }
public static string SendHttpRequest(string url, List <KeyValuePair <String, String> > paramList, string contentType = "application/x-www-form-urlencoded") { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); System.Net.Http.FormUrlEncodedContent content = new System.Net.Http.FormUrlEncodedContent(paramList); content.Headers.ContentType.MediaType = contentType; System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(new Uri(url), content).Result; string res = response.Content.ReadAsStringAsync().Result; return(res); }
/// <summary> /// Retrieves a string by using a http post to a remote url. /// </summary> /// <param name="request"></param> /// <returns></returns> private async Task <HttpResult> LoadFromUrlByPost(HttpDataRequest request) { var uri = BuildRequestUrl(request); var content = CreateHttpContentFromRequest(request); var response = await client.PostAsync(uri, content); var result = await ConvertHttpResponseToHttpResult(response, request.ResultIsList); return(result); }
public async Task <bool> AddItemAsync(Review item) { var client = new System.Net.Http.HttpClient(); StringContent jsonData = new StringContent(ReviewToJSON(item, Preferences.Get("username", "")), Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://iab330.rbvea.co/api/reviews/create", jsonData); return(true); }
private void logoutBtn_Click(object sender, RoutedEventArgs e) { using (var client = new System.Net.Http.HttpClient()) { var content = new StringContent(JsonConvert.SerializeObject(App.CurrentUser), Encoding.UTF8, "application/json"); var result = client.PostAsync($"{App.BaseUri}/offlineUser", content).Result; } myApp.MyHubConnection.Dispose(); Frame.Navigate(typeof(MainPage)); }
/// <summary> /// /// </summary> /// <param name="api"></param> /// <param name="paramList"></param> /// <param name="PostORGet">默认为post请求</param> /// <param name="fulluri"></param> /// <returns></returns> 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; })); }
/// <summary> /// for parameterless requests /// </summary> /// <typeparam name="TRes"></typeparam> /// <param name="actionUrl">action url except base api url</param> /// <param name="methodType">request method type</param> /// <returns></returns> public async Task <HttpClientResponse <TRes> > InvokeApi <TRes>(string actionUrl, WebMethodType methodType = WebMethodType.Post) { Uri url = new Uri(new Uri(_apiBaseUrl), actionUrl); using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); switch (methodType) { case WebMethodType.Get: using (var response = await client.GetAsync(url)) { if (response.StatusCode != HttpStatusCode.OK) { return(new HttpClientResponse <TRes> { HttpStatusCode = response.StatusCode }); } var data = await response.Content.ReadAsStringAsync(); var json = GetParsedData <TRes>(data); //JObject.Parse(data); return(new HttpClientResponse <TRes> { HttpStatusCode = response.StatusCode, ResponseData = json }); } case WebMethodType.Post: using (var response = await client.PostAsync(url, null)) { if (response.StatusCode != HttpStatusCode.OK) { return(new HttpClientResponse <TRes> { HttpStatusCode = response.StatusCode }); } var data = await response.Content.ReadAsStringAsync(); var json = GetParsedData <TRes>(data); //JObject.Parse(data); return(new HttpClientResponse <TRes> { HttpStatusCode = response.StatusCode, ResponseData = json }); } default: throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null); } } }
/// <summary> /// Post请求Json数据 /// </summary> /// <typeparam name="U">请求POCO类型</typeparam> /// <typeparam name="V">响应POCO类型</typeparam> /// <param name="relatedUrl">相对url,可含参数</param> /// <param name="reqObj">请求POCO实例</param> /// <param name="paraMode">参数模式</param> /// <returns>响应POCO实例</returns> public async Task <V> PostJson <U, V>(string relatedUrl, U reqObj, ParaMode paraMode = ParaMode.UrlPara) { this.Headers.Accept.TryParseAdd("application/json"); var paras = ObjToStrParas(reqObj); HttpContent content; switch (paraMode) { case ParaMode.UrlPara: var paraStr = relatedUrl.Contains('?') ? "&" : "?" + string.Join("&", paras.Select(para => para.Key + "=" + WebUtility.UrlEncode(para.Value))); relatedUrl += paraStr; content = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >()); break; case ParaMode.FormPara: content = new FormUrlEncodedContent(paras); break; default: content = new StringContent(JsonConvert.SerializeObject(reqObj), Encoding.UTF8, "application/json"); break; } try { var response = await client.PostAsync(relatedUrl, content).ConfigureAwait(false); var data = response.Content.ReadAsStringAsync().Result; if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine(response.StatusCode); Console.WriteLine(data); return(default(V)); } return(JsonConvert.DeserializeObject <V>(response.Content.ReadAsStringAsync().Result)); } catch { openFlag[0] = false; throw; } }
/// <summary> /// todo:字典不允许重复的键,要改 /// </summary> /// <param name="url"></param> /// <param name="formData"></param> /// <param name="userAgent"></param> /// <returns></returns> public static async Task <string> PostFormResponTextAsync(this string url, Dictionary <string, string> formData, string userAgent = null) { using (var client = new System.Net.Http.HttpClient()) { if (!string.IsNullOrWhiteSpace(userAgent)) { client.DefaultRequestHeaders.Add("User-Agent", userAgent); } return(await(await client.PostAsync(url, new FormUrlEncodedContent(formData))).Content.ReadAsStringAsync()); } }
/// <summary> /// 异步获取post实体 /// </summary> /// <param name="url">url</param> /// <param name="content">post内容,这里直接用基类</param> /// <param name="userAgent">UA</param> /// <returns></returns> public static async Task <string> PostResponTextAsync(this string url, HttpContent content, string userAgent = null) { using (var client = new System.Net.Http.HttpClient()) { if (!string.IsNullOrWhiteSpace(userAgent)) { client.DefaultRequestHeaders.Add("User-Agent", userAgent); } return(await(await client.PostAsync(url, content)).Content.ReadAsStringAsync()); } }
private static async Task SongsControllerTest(HttpClient client) { // create songs await client.PostAsync("Songs/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "qka pesen 007"), new KeyValuePair<string, string>("artistid", "2") })); await client.PostAsync("Songs/Create", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "qka pesen 008"), new KeyValuePair<string, string>("artistid", "2") })); // get all songs Console.WriteLine(await client.GetStringAsync("Songs/All")); // update song await client.PutAsync("Songs/Update", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("id", "2"), new KeyValuePair<string, string>("year", "2010"), new KeyValuePair<string, string>("genre", "narodna pesen") })); // delete song await client.DeleteAsync("api/Songs/Delete/1"); }
private static async Task RunTestsAsync(HttpClient client, CancellationToken cancellationToken) { try { // SMS await client.PostAsync("/sms/api/sms/unicorn", new StringContent($"\"hello world! ({DateTimeOffset.UtcNow.ToString("u")})\"", Encoding.UTF8, "application/json"), cancellationToken); await client.GetAsync("/sms/api/sms/unicorn", cancellationToken); // Counter await client.PostAsync("/counter/api/counter", new StringContent(string.Empty), cancellationToken); await client.GetAsync("/counter/api/counter", cancellationToken); await client.GetAsync("/Hosting/CounterService/api/counter", cancellationToken); var request = new HttpRequestMessage(HttpMethod.Get, "/api/counter"); request.Headers.Add("SF-ServiceUri", "fabric:/Hosting/CounterService"); await client.SendAsync(request, cancellationToken); // WebApp await client.GetAsync("/webapp", cancellationToken); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void Register(string username) { try { client = new HttpClient(); var postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("email", username)); HttpContent content = new FormUrlEncodedContent(postData); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); client.PostAsync("http://localhost:3000/User", content) .ContinueWith(postTask => { postTask.Result.EnsureSuccessStatusCode(); client.Dispose(); }); } catch (Exception ex) { } }
public async Task MashapeFacebookLogin() { //NOTE: Check App.xaml.cs for the variables that you need to fill in var targeturi = "https://ismaelc-facebooktest.p.mashape.com/oauth_url"; var client = new System.Net.Http.HttpClient(); HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("consumerKey", App.ConsumerKey), new KeyValuePair<string, string>("consumerSecret", App.ConsumerSecret), new KeyValuePair<string, string>("callbackUrl", App.CallbackUrl) }); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.Add("X-Mashape-Authorization", App.MashapeHeader); progressRing.IsActive = true; btnLogin.IsEnabled = false; var response = await client.PostAsync(targeturi, content); progressRing.IsActive = false; btnLogin.IsEnabled = true; if (response.IsSuccessStatusCode) { string respContent = await response.Content.ReadAsStringAsync(); string loginUrl = await Task.Run(() => JsonObject.Parse(respContent).GetNamedString("url")); WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(loginUrl), new Uri(App.CallbackUrl)); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { btnLogin.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var callBackUrl = WebAuthenticationResult.ResponseData.ToString(); //Where's ParseQueryString when you need it... App.AccessToken = GetParameter(callBackUrl, "accessToken"); //App.AccessSecret = GetParameter(callBackUrl, "accessSecret"); } else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString()); } else { // The user canceled the authentication } } else { //The POST failed, so update the UI accordingly //txtBlockResult.Text = "Error"; } }
public void sendPost() { // Définition des variables qui seront envoyés HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1 HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2 HttpContent fileStreamContent = new StreamContent(paramFileStream); //HttpContent bytesContent = new ByteArrayContent(paramFileBytes); using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String formData.Add(fileStreamContent, "FICHIER", "RETURN.xml"); // formData.Add(bytesContent, "file2", "file2"); try { var response = client.PostAsync(actionUrl, formData).Result; MessageBox.Show(response.ToString()); if (!response.IsSuccessStatusCode) { MessageBox.Show("Erreur de réponse"); } } catch (Exception Error) { MessageBox.Show(Error.Message); } finally { client.CancelPendingRequests(); } } }