private async Task<string> PostRequest(string URL) { System.Diagnostics.Debug.WriteLine("URL:" + URL); Uri requestUri = new Uri(URL); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; HttpResponseMessage httpResponse = new HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.PostAsync(requestUri, null); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine("Response:" + httpResponseBody); return httpResponseBody; } catch (Exception ex) { throw ex; } }
static async void saveXmlHttpResponseToXmlFile(String url) { //get Http response from < String url> // Http.HttpClient httpClient = new Http.HttpClient(); try { Http.HttpResponseMessage response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); Byte[] content_in_bytes = await response.Content.ReadAsByteArrayAsync(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding e = Encoding.GetEncoding(1251); Decoder d = e.GetDecoder(); int char_count = d.GetCharCount(content_in_bytes, 0, content_in_bytes.Length); Char[] content_in_chars = new Char[char_count]; int chars_decoded_count = d.GetChars(content_in_bytes, 0, content_in_bytes.Length, content_in_chars, char_count, false); Console.WriteLine("{0}", content_in_chars); } catch (Http.HttpRequestException e) { Console.WriteLine("{0}", e); } }
public async void postAPI(Task task) { try { Uri sUrl = new Uri(@"http://localhost:50157/api/tasks/post"); System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); //construct json var json = Newtonsoft.Json.JsonConvert.SerializeObject(task); var content = new StringContent(json, Encoding.UTF8, "application/json"); System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage { Method = System.Net.Http.HttpMethod.Post, RequestUri = sUrl, Content = content }; System.Net.Http.HttpResponseMessage response = await httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var httpResponseBody = await response.Content.ReadAsStringAsync(); Task ta = new Task(httpResponseBody); Task d = tup.Item2.Where(x => x.TaskId == ta.TaskId).Single(); d.Status = ta.Status; d.Note = ta.Note; this.Frame.Navigate(typeof(TaskIndex), tup.Item2); } catch (HttpRequestException e) { Debug.WriteLine("\nException Message : " + e.InnerException.Message); } }
public async System.Threading.Tasks.Task <string> Put <T>(string uri, T data) { using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient()) { System.Net.Http.Headers.MediaTypeHeaderValue mediaType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings(); JsonNetFormatter jsonFormatter = new JsonNetFormatter(jsonSerializerSettings); System.Net.Http.ObjectContent content = new System.Net.Http.ObjectContent <T>(data , new System.Net.Http.Formatting.JsonMediaTypeFormatter() ); System.Net.Http.HttpResponseMessage response = await httpClient.PutAsync(uri, content); response.EnsureSuccessStatusCode(); return(response.Content.ReadAsStringAsync().Result); /* * var requestMessage = new System.Net.Http.HttpRequestMessage * (data, mediaType, new System.Net.Http.Formatting.MediaTypeFormatter[] { jsonFormatter }); * * // var result = httpClient.PutAsync("_endpoint", requestMessage.Content).Result; * // return result.Content.ReadAsStringAsync().Result; */ } }
public override Result CreateResult(HttpResponseMessage responseMessage, IContext context) { responseMessage.EnsureSuccessStatusCode(); ProcessEventsUntilStopped(responseMessage, context); return null; }
public async Task <string> GetData(string endpoint) { System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(endpoint); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); }
public static async Task<string> getInfo(string URL) { HttpClient client = new HttpClient(); HttpResponseMessage response = new HttpResponseMessage(); response = await client.GetAsync(URL); response.EnsureSuccessStatusCode(); Response = await response.Content.ReadAsStringAsync(); return Response; }
public async Task middleware_should_set_the_correct_response_time_custom_header(string url) { HttpClient client = _factory.CreateClient(); AddAuthToken(ref client); System.Net.Http.HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); response.Headers.GetValues("X-Response-Time-ms").ShouldNotBeEmpty(); }
/// <summary> /// Download one Maven package and extract it to the target directory. /// </summary> /// <param name="purl">Package URL of the package to download.</param> /// <returns>n/a</returns> public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false) { Logger.Trace("DownloadVersion {0}", purl?.ToString()); string? packageNamespace = purl?.Namespace?.Replace('.', '/'); string? packageName = purl?.Name; string? packageVersion = purl?.Version; List <string> downloadedPaths = new(); if (string.IsNullOrWhiteSpace(packageNamespace) || string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(packageVersion)) { Logger.Warn("Unable to download [{0} {1} {2}]. Both must be defined.", packageNamespace, packageName, packageVersion); return(downloadedPaths); } try { string[] suffixes = new string[] { "-javadoc", "-sources", "" }; foreach (string suffix in suffixes) { string url = $"{ENV_MAVEN_ENDPOINT}/{packageNamespace}/{packageName}/{packageVersion}/{packageName}-{packageVersion}{suffix}.jar"; HttpClient httpClient = CreateHttpClient(); System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(url); result.EnsureSuccessStatusCode(); Logger.Debug($"Downloading {purl}..."); string targetName = $"maven-{packageNamespace}-{packageName}{suffix}@{packageVersion}"; targetName = targetName.Replace('/', '-'); string extractionPath = Path.Combine(TopLevelExtractionDirectory, targetName); if (doExtract && Directory.Exists(extractionPath) && cached == true) { downloadedPaths.Add(extractionPath); return(downloadedPaths); } if (doExtract) { downloadedPaths.Add(await ArchiveHelper.ExtractArchiveAsync(TopLevelExtractionDirectory, targetName, await result.Content.ReadAsStreamAsync(), cached)); } else { extractionPath += Path.GetExtension(url) ?? ""; await File.WriteAllBytesAsync(extractionPath, await result.Content.ReadAsByteArrayAsync()); downloadedPaths.Add(extractionPath); } } } catch (Exception ex) { Logger.Warn(ex, "Error downloading Maven package: {0}", ex.Message); } return(downloadedPaths); }
public async Task <string> PostData(string data, string endpoint) { var stringContent = new StringContent(data, UnicodeEncoding.UTF8, "application/json"); System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(endpoint, stringContent); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); }
// http://www.thomaslevesque.com/2013/11/30/uploading-data-with-httpclient-using-a-push-model/ async System.Threading.Tasks.Task UploadJsonObject0Async <T>(System.Uri uri, T data) { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(data); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, new System.Net.Http.StringContent(json)); response.EnsureSuccessStatusCode(); } }
async System.Threading.Tasks.Task UploadJsonObject2Async <T>(System.Uri uri, T data) { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { System.Net.Http.ObjectContent content = new System.Net.Http.ObjectContent <T>(data , new System.Net.Http.Formatting.JsonMediaTypeFormatter() ); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, content); response.EnsureSuccessStatusCode(); } }
public async System.Threading.Tasks.Task <Newtonsoft.Json.Linq.JObject> PostAsync(string uri, string data) { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(uri, new System.Net.Http.StringContent(data)); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); return(await System.Threading.Tasks.Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(content))); }
/// <summary> /// Download one Hackage (Haskell) package and extract it to the target directory. /// </summary> /// <param name="purl"> Package URL of the package to download. </param> /// <returns> n/a </returns> public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false) { Logger.Trace("DownloadVersion {0}", purl?.ToString()); if (purl is null || purl.Name is null || purl.Version is null) { return(Array.Empty <string>()); } string packageName = purl.Name; string packageVersion = purl.Version; if (string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(packageVersion)) { Logger.Debug("Unable to download [{0} {1}]. Both must be defined.", packageName, packageVersion); return(Array.Empty <string>()); } List <string> downloadedPaths = new(); try { string url = $"{ENV_HACKAGE_ENDPOINT}/package/{packageName}-{packageVersion}/{packageName}-{packageVersion}.tar.gz"; HttpClient httpClient = CreateHttpClient(); System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(url); result.EnsureSuccessStatusCode(); Logger.Debug("Downloading {0}...", purl.ToString()); string targetName = $"hackage-{packageName}@{packageVersion}"; string extractionPath = Path.Combine(TopLevelExtractionDirectory, targetName); if (doExtract && Directory.Exists(extractionPath) && cached == true) { downloadedPaths.Add(extractionPath); return(downloadedPaths); } if (doExtract) { downloadedPaths.Add(await ArchiveHelper.ExtractArchiveAsync(TopLevelExtractionDirectory, targetName, await result.Content.ReadAsStreamAsync(), cached)); } else { extractionPath += Path.GetExtension(url) ?? ""; await File.WriteAllBytesAsync(extractionPath, await result.Content.ReadAsByteArrayAsync()); downloadedPaths.Add(extractionPath); } } catch (Exception ex) { Logger.Debug(ex, "Error downloading Hackage package: {0}", ex.Message); } return(downloadedPaths); }
/// <summary> /// Download one Cargo package and extract it to the target directory. /// </summary> /// <param name="purl"> Package URL of the package to download. </param> /// <returns> Path to the downloaded package </returns> public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false) { Logger.Trace("DownloadVersion {0}", purl?.ToString()); string? packageName = purl?.Name; string? packageVersion = purl?.Version; string? fileName = purl?.ToStringFilename(); List <string> downloadedPaths = new(); if (string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(packageVersion) || string.IsNullOrWhiteSpace(fileName)) { Logger.Debug("Error with 'purl' argument. Unable to download [{0} {1}] @ {2}. Both must be defined.", packageName, packageVersion, fileName); return(downloadedPaths); } string url = $"{ENV_CARGO_ENDPOINT}/api/v1/crates/{packageName}/{packageVersion}/download"; try { string targetName = $"cargo-{fileName}"; string extractionPath = Path.Combine(TopLevelExtractionDirectory, targetName); // if the cache is already present, no need to extract if (doExtract && cached && Directory.Exists(extractionPath)) { downloadedPaths.Add(extractionPath); return(downloadedPaths); } Logger.Debug("Downloading {0}", url); HttpClient httpClient = CreateHttpClient(); System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(url); result.EnsureSuccessStatusCode(); if (doExtract) { downloadedPaths.Add(await ArchiveHelper.ExtractArchiveAsync(TopLevelExtractionDirectory, targetName, await result.Content.ReadAsStreamAsync(), cached)); } else { extractionPath += Path.GetExtension(url) ?? ""; await File.WriteAllBytesAsync(extractionPath, await result.Content.ReadAsByteArrayAsync()); downloadedPaths.Add(extractionPath); } } catch (Exception ex) { Logger.Debug(ex, "Error downloading Cargo package: {0}", ex.Message); } return(downloadedPaths); }
/// <summary> /// Initializes connection to Hue bridge /// </summary> /// <param name="url"></param> /// <param name="username"></param> public void Initialize(string url, string username) { if (url.LastIndexOf('/') == url.Length - 1) { url = url.Substring(0, url.Length - 1); } //connect to bridge using IP address from config file //assume connected app and username from config file //ping bridge to ensure connectivity _bridgeApiBase = new Uri(string.Format("{0}/api/{1}", url, username)); try { HttpResponseMessage response = new HttpResponseMessage(); // Create a Http Call for Access Token HttpClient client = new HttpClient(); client.BaseAddress = _bridgeApiBase; client.GetAsync(_bridgeApiBase + "/lights").ContinueWith( (getTask) => { if (getTask.IsCanceled) { return; } if (getTask.IsFaulted) { throw getTask.Exception; } response = getTask.Result; response.EnsureSuccessStatusCode(); }).Wait(); string result = response.Content.ReadAsStringAsync().Result.ToString(); this.Lights = new Dictionary<string, Light>(); JToken token = JToken.Parse(result); if (token.Type == JTokenType.Object) { var lightsJSON = (JObject)token; foreach (var prop in lightsJSON.Properties()) { Light newLight = JsonConvert.DeserializeObject<Light>(prop.Value.ToString()); newLight.Id = prop.Name.ToString(); this.Lights.Add(newLight.Name.ToLower(), newLight); } } } catch (Exception ex) { throw new Exception("Error initializing HueManager. Check inner exception for details.", ex); } }
private async Task<bool> EnsureSuccessOrThrow(HttpResponseMessage resp) { if (resp.IsSuccessStatusCode) { return true; } if (resp.StatusCode == HttpStatusCode.BadRequest || resp.StatusCode == HttpStatusCode.InternalServerError) { var msg = await resp.Content.ReadAsStringAsync(); throw new SelfossServerException(msg, null); } resp.EnsureSuccessStatusCode(); return true; }
public async Task <String> FileUpload(StorageFile file) { HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); var bytes = await GetBytesAsync(file); form.Add(new ByteArrayContent(bytes, 0, bytes.Length), "client", "client"); System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(host + "/upload/version", form); response.EnsureSuccessStatusCode(); httpClient.Dispose(); return(await response.Content.ReadAsStringAsync()); }
public void EnsureSuccessStatusCode() { HttpResponseMessage message = new HttpResponseMessage (); Assert.AreSame (message, message.EnsureSuccessStatusCode (), "#1"); message = new HttpResponseMessage (HttpStatusCode.BadRequest); message.ReasonPhrase = "test reason"; try { message.EnsureSuccessStatusCode (); Assert.Fail ("#2"); } catch (HttpRequestException e) { Assert.IsTrue (e.Message.Contains ("400 (test reason)"), "#3"); } }
/// <summary> /// Download one RubyGems package and extract it to the target directory. /// </summary> /// <param name="purl"> Package URL of the package to download. </param> /// <returns> n/a </returns> public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false) { Logger.Trace("DownloadVersion {0}", purl?.ToString()); string? packageNamespace = purl?.Namespace; string? packageName = purl?.Name; string? packageVersion = purl?.Version; List <string> downloadedPaths = new(); if (string.IsNullOrWhiteSpace(packageNamespace) || string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(packageVersion)) { Logger.Debug("Unable to download [{0} {1} {2}]. All three must be defined.", packageNamespace, packageName, packageVersion); return(downloadedPaths); } try { string url = $"{ENV_GO_PROXY_ENDPOINT}/{packageNamespace.ToLowerInvariant()}/{packageName.ToLowerInvariant()}/@v/{packageVersion}.zip"; HttpClient httpClient = CreateHttpClient(); System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(url); result.EnsureSuccessStatusCode(); Logger.Debug("Downloading {0}...", purl); string targetName = $"golang-{packageNamespace}-{packageName}@{packageVersion}"; string extractionPath = Path.Combine(TopLevelExtractionDirectory, targetName); if (doExtract && Directory.Exists(extractionPath) && cached == true) { downloadedPaths.Add(extractionPath); return(downloadedPaths); } if (doExtract) { downloadedPaths.Add(await ArchiveHelper.ExtractArchiveAsync(TopLevelExtractionDirectory, targetName, await result.Content.ReadAsStreamAsync(), cached)); } else { extractionPath += Path.GetExtension(url) ?? ""; await File.WriteAllBytesAsync(extractionPath, await result.Content.ReadAsByteArrayAsync()); downloadedPaths.Add(extractionPath); } } catch (Exception ex) { Logger.Debug(ex, "Error downloading Go package: {0}", ex.Message); } return(downloadedPaths); }
// https://www.jayway.com/2012/01/18/webclientwebrequest-threading-untangled/ // https://www.jayway.com/2012/03/13/httpclient-makes-get-and-post-very-simple/ public async System.Threading.Tasks.Task <Newtonsoft.Json.Linq.JObject> GetAsync(string uri) { using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient()) { System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(uri); //will throw an exception if not successful response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); return(await System.Threading.Tasks.Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(content))); } }
public async Task <string> GetData(string url) { string responseBody = null; var uri = new Uri(url); System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(uri); response.EnsureSuccessStatusCode(); responseBody = response.Content.ReadAsStringAsync().Result; return(responseBody); }
static void Ex4() { System.Threading.Tasks.Task.Run(async() => { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(new HttpClientHandler() { UseProxy = false }); System.Net.Http.HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://www.albahari.com/EchoPost.aspx"); request.Content = new StringContent("Ex4"); System.Net.Http.HttpResponseMessage response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); }); }
static void Ex2() { System.Threading.Tasks.Task.Run(async() => { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage response = await client.GetAsync("http://www.linqpad.net"); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); using (System.IO.FileStream fs = System.IO.File.Create("Ex2.txt")) { await response.Content.CopyToAsync(fs); } System.Diagnostics.Process.Start("Ex2.txt"); }); }
static void Ex3() { System.Threading.Tasks.Task.Run(async() => { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); System.Net.Http.HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://www.linqpad.net"); System.Net.Http.HttpResponseMessage response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); using (System.IO.FileStream fs = System.IO.File.Create("Ex3.html")) { await response.Content.CopyToAsync(fs); } System.Diagnostics.Process.Start("Ex3.html"); }); }
public KnowledgeBaseDetails GetDetails() { if (null != this.details) { return(this.details); } using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { string RequestURI = $"https://{this.azureServicName}.{baseUrl}/qnamaker/v4.0/knowledgebases/"; client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey); System.Net.Http.HttpResponseMessage msg = client.GetAsync(RequestURI).Result; msg.EnsureSuccessStatusCode(); var JsonDataResponse = msg.Content.ReadAsStringAsync().Result; KnowledgeBaseListAllRootObject allKBs = JsonConvert.DeserializeObject <KnowledgeBaseListAllRootObject>(JsonDataResponse); if (null == allKBs) { throw new JsonException("Could not deserialize the list of knowledgebases"); } if (!string.IsNullOrEmpty(this.knowledgeBaseId)) { this.details = allKBs.knowledgebases.FirstOrDefault(p => p.id == this.knowledgeBaseId); return(this.details); } var allDetails = allKBs.knowledgebases.Where(p => p.name == this.knowledgebase).ToArray(); if (allDetails.Length == 0) { return(null); } if (allDetails.Length > 1) { throw new KeyNotFoundException($"More than one Knowledge base found with name {this.knowledgebase}, please pass in knowledge base id to differentiate them"); } this.details = allDetails[0]; return(this.details); } }
private async Task<string> WebPageToString(string link) { HttpClient httpClient = new HttpClient(); Uri requestUri = new Uri(link); HttpResponseMessage httpResponse = new HttpResponseMessage(); string httpResponseBody = string.Empty; try { httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = string.Format("Error: {0} Message: ", ex.HResult.ToString("X"), ex.Message); } return httpResponseBody; }
public async Task<string> Get(string baseURI, string uri, bool authenticate = true) { await CheckAPIResponsiveness(); if (authenticate) { await AddAuthenticationHeader(); } HttpResponseMessage response = new HttpResponseMessage(); Client.BaseAddress = new Uri(baseURI); response = await Client.GetAsync(uri); response.EnsureSuccessStatusCode(); TokenManager.LastRefresh = DateTime.UtcNow; return await response.Content.ReadAsStringAsync(); }
/** * Concatenate a Uri with the given parameters. * If uri invokation was succesfull a list with all users for the given eventId and state will be created, * which will be stored in the variable listUser. **/ public async Task<List<MySqlUser>> SelectUserForEvent(string host, int idEvent, string state) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/requestUserForEvent.php?idEvent=" + idEvent + "&state=" + state); List<MySqlUser> listUser = null; string responseText; try { response = await client.GetAsync(uri).ConfigureAwait(continueOnCapturedContext:false); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext:false); listUser = createUserFromResponse(responseText); } catch(Exception e) { Console.WriteLine("Error while selecting data from MySQL: " + e.Message); } return listUser; }
public string GetSync(string addr) { HttpClientHandler handler = new HttpClientHandler(); if (m_useAuth) { handler.CookieContainer = new System.Net.CookieContainer(); if (string.IsNullOrEmpty(m_authTicket)) { try { m_authTicket = Feng.UserManager.UserManagerHelper.GetFormsAuthenticationTicket(); } catch (Exception ex) { ExceptionProcess.ProcessWithResume(ex); m_useAuth = false; } } handler.CookieContainer.Add(new Uri(SystemConfiguration.Server), new System.Net.Cookie(Feng.UserManager.UserManagerHelper.UserAuthenticationCookieName, m_authTicket)); } HttpClient client = new HttpClient(handler); client.MaxResponseContentBufferSize = 5242880; var t = client.GetAsync(addr).ContinueWith((requestTask) => { System.Net.Http.HttpResponseMessage response = requestTask.Result; if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new InvalidOperationException("Invalid Rest Service with StatusCode of " + response.StatusCode); } response.EnsureSuccessStatusCode(); var t2 = response.Content.ReadAsStringAsync().ContinueWith((readTask) => { string s = readTask.Result; return(s); }); return(t2.Result); }); t.Wait(); return(t.Result); }
async System.Threading.Tasks.Task UploadJsonObject1Async <T>(System.Uri uri, T data) { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { System.Net.Http.PushStreamContent content = new System.Net.Http.PushStreamContent((stream, httpContent, transportContext) => { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); using (System.IO.TextWriter writer = new System.IO.StreamWriter(stream)) { serializer.Serialize(writer, data); } }); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, content); response.EnsureSuccessStatusCode(); } }
private void Ex3() { string uri = "http://www.albahari.com/EchoPost.aspx"; var client = new HttpClient(); var dict = new System.Collections.Generic.Dictionary <string, string>() { { "Name", "Giang" }, { "Company", "Ex3" } }; System.Net.Http.FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(dict); System.Threading.Tasks.Task.Run(async() => { System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, formUrlEncodedContent); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); }); }
private async void UploadButton_Click(object sender, RoutedEventArgs e) { if (IsUpload == true) { // 将当前文件夹中的图片全部上传 if (fileList != null) { // 上传文件的表单 MultipartFormDataContent form = new MultipartFormDataContent(); foreach (StorageFile file_ in fileList) { Stream fileStream = await file_.OpenStreamForReadAsync(); StreamContent streamContent = new StreamContent(fileStream); form.Add(streamContent, "file", file_.Name); } var headers = httpClient.DefaultRequestHeaders; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } try { httpResponse = await httpClient.PostAsync(requestUri, form); httpResponse.EnsureSuccessStatusCode(); string httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { string httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; } } var dialog = new MessageDialog("照片上传成功", "上传提示"); dialog.Commands.Add(new UICommand("确定", cmd => { }, commandId: 0)); await dialog.ShowAsync(); IsUpload = false; UploadButton.Opacity = 0; } }
public static void PostAsync(string _URL, object _DATA, TConnector.ConnectorOnEventDelegate _onresponse = null, TConnector.ConnectorOnEventDelegate _onerror = null) { var client = new HttpClient(); byte[] bytes; bytes = System.Text.Encoding.ASCII.GetBytes(_DATA.ToString()); HttpContent content = new ByteArrayContent(bytes); client.PostAsync(_URL, content).ContinueWith( (postTask) => { object retval; HttpResponseMessage msg = new HttpResponseMessage(); try { msg = postTask.Result; msg.EnsureSuccessStatusCode(); } catch (Exception ex) { if (_onerror != null) _onerror(ex); return; } Task<Stream> objResponseStreamTask = msg.Content.ReadAsStreamAsync(); Stream objResponseStream = objResponseStreamTask.Result; XmlDocument xmldoc = new XmlDocument(); try { XmlTextReader objXMLReader = new XmlTextReader(objResponseStream); xmldoc.Load(objXMLReader); objXMLReader.Close(); retval = xmldoc; } catch (Exception) { objResponseStream.Position = 0; StreamReader sr = new StreamReader(objResponseStream); retval = sr.ReadToEnd(); } if (_onresponse != null) _onresponse(retval); }); }
public static async Task <string> PostFormAsync(string url, Dictionary <string, string> parameters) { string result = null; using (var httpClient = new System.Net.Http.HttpClient()) { MultipartFormDataContent form = new MultipartFormDataContent(); foreach (KeyValuePair <string, string> item in parameters) { form.Add(new StringContent(item.Value), item.Key); } System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(url, form); response.EnsureSuccessStatusCode(); Task <string> responseBody = response.Content.ReadAsStringAsync(); result = responseBody.Result; } return(result); }
protected virtual async System.Threading.Tasks.Task <O> GetAsync <O>() { System.Net.Http.HttpResponseMessage response = null; try { response = await Http.GetAsync(requestUri : RequestUri); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { try { O result = await response.Content.ReadFromJsonAsync <O>(); return(result); } // When content type is not valid catch (System.NotSupportedException) { System.Console.WriteLine("The content type is not supported."); } // Invalid JSON catch (System.Text.Json.JsonException) { System.Console.WriteLine("Invalid JSON."); } } } catch (System.Net.Http.HttpRequestException ex) { System.Console.WriteLine(ex.Message); } finally { response.Dispose(); } return(default);
public async Task<MySqlUser> validateLogin(string host, string username, string password) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/validateLogin.php?username="******"&password="******"Login uri: " + uri); MySqlUser user = null; string responseText; try { response = await client.GetAsync(uri).ConfigureAwait(continueOnCapturedContext:false); Console.WriteLine("selectuser - response statuscode = " + response.StatusCode); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext:false); user = createUserFromResponse(responseText)[0]; if(debug) Console.WriteLine("Login response: " + responseText); } catch(Exception e) { Console.WriteLine("Error while loging in: " + e.Message + " Source: " + e.InnerException + " | " + e.StackTrace); } return user; }
/** * Delets a user with the given userId. * You can check if the insert was succesful in the succes variable. **/ public async Task<bool> DeleteUser(string host, int idUser) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/deleteUser.php" + "?idUser="******"Delete response: " + responseText); } } catch(Exception e) { Console.WriteLine("Error while selecting data from MySQL: " + e.Message); return false; } return false; }
/** * Inserts a user with the given parameters and userId = currentHighestId + 1. * You can check if the insert was succesful in the succes variable. **/ public async Task<bool> InsertUser(string host, string name, string role, string password, int number, string position) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/insertUser.php" + "?name=" + name + "&role=" + role + "&password="******"&number=" + number + "&position=" + position); string responseText; try { response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); if(dbCommunicator.wasSuccesful(responseText)) { return true; } if(debug) { Console.WriteLine("Insert response: " + responseText); } } catch(Exception e) { Console.WriteLine("Error while selecting data from MySQL: " + e.Message); return false; } return false; }
public async Task<string> Put(string uri, String rawJSON) { await CheckAPIResponsiveness(); await AddAuthenticationHeader(); string returnString = ""; Client.BaseAddress = new Uri(StringConstants.APIMemberURL); var contentPost = new StringContent(rawJSON, Encoding.UTF8, "application/json"); HttpResponseMessage response = new HttpResponseMessage ();; response = await Client.PutAsync(uri, contentPost); returnString = response.Content.ReadAsStringAsync().Result; if (returnString.Contains ("422")) { var objectJ = JObject.Parse(returnString); // parse as array string description = (String)objectJ ["Message"]; var exception = new Exception (description); throw exception; } else { response.EnsureSuccessStatusCode(); } TokenManager.LastRefresh = DateTime.UtcNow; return returnString; }
private async void connectHttp(string address, string UserID, string EmployeeName, string SupervisorID, string Location, string Reason, string CheckType) { response = new HttpResponseMessage(); string responseText; Uri resourceUri; if (!Uri.TryCreate(address.Trim(), UriKind.Absolute, out resourceUri)) { //return "Invalid URI, please re-enter a valid URI"; return; } if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https") { //return "Only 'http' and 'https' schemes supported. Please re-enter URI"; return; } // ---------- end of test--------------------------------------------------------------------- try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add((new StringContent(UserID, System.Text.Encoding.UTF8, "text/plain")), "UserID"); content.Add((new StringContent(EmployeeName, System.Text.Encoding.UTF8, "text/plain")), "EmployeeName"); content.Add((new StringContent(SupervisorID, System.Text.Encoding.UTF8, "text/plain")), "SupervisorID"); content.Add((new StringContent(Location, System.Text.Encoding.UTF8, "text/plain")), "Location"); content.Add((new StringContent(Reason, System.Text.Encoding.UTF8, "text/plain")), "Reason"); content.Add((new StringContent(CheckType, System.Text.Encoding.UTF8, "text/plain")), "CheckType"); response = await httpClient.PostAsync(resourceUri, content); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { // Need to convert int HResult to hex string //Result.Text = "Error = " + ex.HResult.ToString("X") + // " Message: " + ex.Message; responseText = ""; } }
/// <summary> /// Posts a API command for a single light to the Hue Bridge. Used to change the State of a light. /// </summary> /// <param name="light"></param> /// <param name="command"></param> private void SendApiCommand(Light light, string command) { try { HttpResponseMessage response = new HttpResponseMessage(); // Create a Http Call for Access Token HttpClient client = new HttpClient(); client.BaseAddress = _bridgeApiBase; client.PutAsync(_bridgeApiBase + "/lights/" + light.Id.ToString() + "/state", new StringContent(command)).ContinueWith( (getTask) => { if (getTask.IsCanceled) { return; } if (getTask.IsFaulted) { throw getTask.Exception; } response = getTask.Result; response.EnsureSuccessStatusCode(); }).Wait(); string result = response.Content.ReadAsStringAsync().Result.ToString(); } catch (Exception ex) { throw new Exception("Error sending command. Check inner exception for details.", ex); } }
/// <summary> /// Asynchronously processes an HTTP response message, ensuring it was successful and extracting its content. /// </summary> private static async Task<HttpResponse> ProcessResponseAsync( HttpResponseMessage response, Encoding encoding ) { // HACK: If it's a redirect, just return an empty response, we're interested in the cookies if ( (int) response.StatusCode / 100 == 3 ) { return new HttpResponse( "", "" ); } response.EnsureSuccessStatusCode(); byte[] bytes = await response.Content.ReadAsByteArrayAsync(); string content = encoding.GetString( bytes, 0, bytes.Length ); string requestUrl = response.RequestMessage.RequestUri.ToString(); return new HttpResponse( content, requestUrl ); }
public static void PrintResponse(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); Console.WriteLine("Response:"); Console.WriteLine(response); if (response.Content != null) { Console.WriteLine(response.Content.ReadAsStringAsync().Result); } }
public virtual void EnsureSuccess(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); }
private static async Task<ProcessorRuntimeStatus[]> GetHttpResponseAsRuntimeStatusAsync(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); string sJson = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<ProcessorRuntimeStatus[]>(sJson); }
private async Task UpdateScheduledTimesList( HttpResponseMessage response) { response.EnsureSuccessStatusCode(); var shifts = await GetShiftStringsAsync(this.Client); var list = ScheduledTimeList.Parse(shifts, StartRegexFormat, EndRegexFormat, Sync); list.Sort((a, b) => a.Start.CompareTo(b.Start)); this.Content = list; }
/// <summary> /// Handles processing a response from the server /// </summary> /// <param name="response">HttpResponseMessage from the server</param> /// <returns>Task<string></returns> /// <exception cref="System.Security.Authentication.InvalidCredentialException">Thrown when an invalid username or password is supplied.</exception> /// <exception cref="CiresonPortalAPI.CiresonApiException">Thrown when an internal server error (HTTP 500) occurs.</exception> /// <exception cref="System.Net.Http.HttpRequestException">Thrown when any other HTTP exception occurs.</exception> private async Task<string> ProcessResponse(HttpResponseMessage response) { string result = string.Empty; if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsStringAsync(); } else if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) { throw new InvalidCredentialException("Invalid username or password."); } else if (response.StatusCode == HttpStatusCode.InternalServerError) { // Get the error message from the server result = await response.Content.ReadAsStringAsync(); throw new CiresonApiException(result); } else { // Other unhandled errors try { response.EnsureSuccessStatusCode(); } catch (HttpRequestException) { // Rethrow exception throw; } } return result; }
private static async Task HandleErrorResponse(HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return; } // In case of errors, the response should contain additional textual information // formatted as key=value pairs separated by the \n character. if (response.Content != null) { var mediaType = response.Content.Headers?.ContentType?.MediaType; if (string.Equals(mediaType, "text/plain")) { var textResponseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var detailsToInclude = textResponseBody?.Split('\n') .Select(s => s.Trim()) .Where(s => s.Length > 0) .Where(v => ErrorResponseKeysToIncludeInExceptionDetails.Any(key => v.StartsWith(key, StringComparison.OrdinalIgnoreCase))) .ToList(); if (detailsToInclude?.Count > 0) { throw new Exception( $"Received error response from SMS connector ({(int) response.StatusCode} {response.ReasonPhrase}). {string.Join("; ", detailsToInclude)}"); } } } response.EnsureSuccessStatusCode(); }
private async Task <byte[]> GetByteArrayAsyncCore(Task <HttpResponseMessage> getTask) { using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false)) { responseMessage.EnsureSuccessStatusCode(); HttpContent content = responseMessage.Content; if (content != null) { HttpContentHeaders headers = content.Headers; Stream stream = content.TryReadAsStream(); if (stream == null) { stream = await content.ReadAsStreamAsync().ConfigureAwait(false); } using (Stream responseStream = stream) { long? contentLength = headers.ContentLength; Stream buffer; if (contentLength.HasValue) { buffer = (Stream) new HttpContent.LimitMemoryStream(this._maxResponseContentBufferSize, (int)contentLength.GetValueOrDefault()); try { await responseStream.CopyToAsync(buffer).ConfigureAwait(false); } catch (Exception ex) when(HttpContent.StreamCopyExceptionNeedsWrapping(ex)) { throw HttpContent.WrapStreamCopyException(ex); } if (buffer.Length > 0L) { return(((HttpContent.LimitMemoryStream)buffer).GetSizedBuffer()); } } else { buffer = (Stream) new HttpContent.LimitArrayPoolWriteStream(this._maxResponseContentBufferSize); try { try { await responseStream.CopyToAsync(buffer).ConfigureAwait(false); } catch (Exception ex) when(HttpContent.StreamCopyExceptionNeedsWrapping(ex)) { throw HttpContent.WrapStreamCopyException(ex); } if (buffer.Length > 0L) { return(((HttpContent.LimitArrayPoolWriteStream)buffer).ToArray()); } } finally { buffer.Dispose(); } } buffer = (Stream)null; } headers = (HttpContentHeaders)null; } return(Array.Empty <byte>()); } }
private async Task UpdateLoginHeaderInformation( HttpResponseMessage response) { response.EnsureSuccessStatusCode(); var getHtmlTask = response.Content.ReadAsStringAsync(); var wbat = response.Headers.GetValues("wbat").First(); this.Client.LoginHeader["wbat"] = wbat; var token = ParseLoginToken(await getHtmlTask); this.Client.LoginHeader["url_login_token"] = token; this.UrlEncodedContent = new FormUrlEncodedContent(this.Client.LoginHeader.Values); }
private async void Save(object sender, RoutedEventArgs e) { phpAddress = "http://localhost/NewsReaderExpress/insNewsPost.php"; //?headLine=" + headLine.Text + "&type=" + rb.Content + "&details=" + details.Text + "&fileName=" + fileName; phpAddress = "http://localhost:21750/NewsReaderExpressPHP/insNewsPost.php"; response = new HttpResponseMessage(); byte[] image = PhotoStreamToBase64(); Uri resourceUri; if (!Uri.TryCreate(phpAddress.Trim(), UriKind.Absolute, out resourceUri)) { phpStatus.Text = "Invalid URI, please re-enter a valid URI"; return; } if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https") { phpStatus.Text = "Only 'http' and 'https' schemes supported. Please re-enter URI"; return; } // ---------- end of test--------------------------------------------------------------------- string responseText; phpStatus.Text = "Waiting for response ..."; try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add((new StringContent(headLine.Text, System.Text.Encoding.UTF8, "text/plain")), "headLine"); content.Add((new StringContent((string)rb.Content, System.Text.Encoding.UTF8, "text/plain")), "type"); content.Add((new StringContent(details.Text, System.Text.Encoding.UTF8, "text/plain")), "details"); content.Add((new StringContent(fileName, System.Text.Encoding.UTF8, "text/plain")), "fileName"); //Uploading the image var imageContent = new ByteArrayContent(image); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); content.Add(imageContent, "image", headLine.Text+".jpg"); /***********/ response = await httpClient.PostAsync(resourceUri, content); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { // Need to convert int HResult to hex string phpStatus.Text = "Error = " + ex.HResult.ToString("X") + " Message: " + ex.Message; responseText = ""; } phpStatus.Text = response.StatusCode + " " + response.ReasonPhrase; // now 'responseText' contains the response as a verified text. // next 'responseText' is displayed phpStatus.Text = responseText.ToString(); //DataSource update= DataSource.returnInstance(); //update.updateNews(phpAddress2); NavigationService.Navigate(new Uri("/PanoramaPage1.xaml", UriKind.RelativeOrAbsolute)); }
private async Task ThrowOnError(HttpResponseMessage response) { if (response.StatusCode == HttpStatusCode.BadRequest) { var content = await response.Content.ReadAsStringAsync(); var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(content); throw new BadRequestException("KairosDb returned status code 400: Bad Request.", errorResponse.Errors); } response.EnsureSuccessStatusCode(); }
/// <inheritdoc /> public override async Task <IEnumerable <string> > EnumerateVersionsAsync(PackageURL purl, bool useCache = true, bool includePrerelease = true) { Logger.Trace("EnumerateVersions {0}", purl?.ToString()); if (purl == null || purl.Name is null) { return(new List <string>()); } try { string packageName = purl.Name; List <string> versionList = new(); HttpClient httpClient = CreateHttpClient(); // Get the latest version System.Net.Http.HttpResponseMessage html = await httpClient.GetAsync($"{ENV_CRAN_ENDPOINT}/web/packages/{packageName}/index.html"); html.EnsureSuccessStatusCode(); HtmlParser?parser = new(); AngleSharp.Html.Dom.IHtmlDocument document = await parser.ParseDocumentAsync(await html.Content.ReadAsStringAsync()); AngleSharp.Dom.IHtmlCollection <AngleSharp.Dom.IElement> tds = document.QuerySelectorAll("td"); for (int i = 0; i < tds.Length; i++) { if (tds[i].TextContent == "Version:") { string?value = tds[i + 1]?.TextContent?.Trim(); if (value != null) { versionList.Add(value); } break; } } // Get the remaining versions html = await httpClient.GetAsync($"{ENV_CRAN_ENDPOINT}/src/contrib/Archive/{packageName}/"); html.EnsureSuccessStatusCode(); document = await parser.ParseDocumentAsync(await html.Content.ReadAsStringAsync()); tds = document.QuerySelectorAll("a"); foreach (AngleSharp.Dom.IElement td in tds) { string?href = td.GetAttribute("href"); if (href?.Contains(".tar.gz") ?? false) { string version = href.Replace(".tar.gz", ""); version = version.Replace(packageName + "_", "").Trim(); Logger.Debug("Identified {0} version {1}.", packageName, version); versionList.Add(version); } } return(SortVersions(versionList.Distinct())); } catch (Exception ex) { Logger.Debug("Unable to enumerate versions: {0}", ex.Message); throw; } }
void EnsureSuccessStatusCode(HttpResponseMessage m) { if (m.StatusCode == HttpStatusCode.Forbidden) { throw new HttpForbiddenException(); } if (m.StatusCode == HttpStatusCode.GatewayTimeout) { throw new HttpConnectionException(); } if (m.StatusCode == HttpStatusCode.NotFound) { throw new HttpNotFoundException(); } m.EnsureSuccessStatusCode(); }
private static void EnsureSuccessStatusCode(HttpResponseMessage response) { if ((int)response.StatusCode < 100) { response.StatusCode = HttpStatusCode.OK; response.ReasonPhrase = "OK"; } string contentTypeMediaType = response.Content?.Headers?.ContentType?.MediaType; bool isNotCCPWithXmlContent = response.RequestMessage.RequestUri.Host != APIProvider.DefaultProvider.Url.Host && response.RequestMessage.RequestUri.Host != APIProvider.TestProvider.Url.Host && contentTypeMediaType != null && !contentTypeMediaType.Contains("xml"); if (isNotCCPWithXmlContent || response.Content?.Headers?.ContentLength == 0) response.EnsureSuccessStatusCode(); }
/// <summary> /// Download one PyPI package and extract it to the target directory. /// </summary> /// <param name="purl">Package URL of the package to download.</param> /// <returns>the path or file written.</returns> public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false) { Logger.Trace("DownloadVersion {0}", purl?.ToString()); string? packageName = purl?.Name; string? packageVersion = purl?.Version; List <string> downloadedPaths = new(); if (string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(packageVersion)) { Logger.Debug("Unable to download [{0} {1}]. Both must be defined.", packageName, packageVersion); return(downloadedPaths); } try { HttpClient httpClient = CreateHttpClient(); JsonDocument?doc = await GetJsonCache(httpClient, $"{ENV_PYPI_ENDPOINT}/pypi/{packageName}/json"); if (!doc.RootElement.TryGetProperty("releases", out JsonElement releases)) { return(downloadedPaths); } foreach (JsonProperty versionObject in releases.EnumerateObject()) { if (versionObject.Name != packageVersion) { continue; } foreach (JsonElement release in versionObject.Value.EnumerateArray()) { if (!release.TryGetProperty("packagetype", out JsonElement packageType)) { continue; // Missing a package type } System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(release.GetProperty("url").GetString()); result.EnsureSuccessStatusCode(); string targetName = $"pypi-{packageType}-{packageName}@{packageVersion}"; string extension = ".tar.gz"; if (packageType.ToString() == "bdist_wheel") { extension = ".whl"; } string extractionPath = Path.Combine(TopLevelExtractionDirectory, targetName); if (doExtract && Directory.Exists(extractionPath) && cached == true) { downloadedPaths.Add(extractionPath); return(downloadedPaths); } if (doExtract) { downloadedPaths.Add(await ArchiveHelper.ExtractArchiveAsync(TopLevelExtractionDirectory, targetName, await result.Content.ReadAsStreamAsync(), cached)); } else { extractionPath += extension; await File.WriteAllBytesAsync(extractionPath, await result.Content.ReadAsByteArrayAsync()); downloadedPaths.Add(extractionPath); } } } } catch (Exception ex) { Logger.Debug(ex, "Error downloading PyPI package: {0}", ex.Message); } return(downloadedPaths); }
public async void getPublicNews() { //string phpAddress = "http://localhost/NewsReaderExpress/viewNewsPost.php"; string phpAddress = "http://localhost:21750/NewsReaderExpressPHP/viewNewsPost.php"; httpClient = new HttpClient(); // Add a user-agent header var headers = httpClient.DefaultRequestHeaders; // HttpProductInfoHeaderValueCollection is a collection of // HttpProductInfoHeaderValue items used for the user-agent header headers.UserAgent.ParseAdd("ie"); headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); response = new HttpResponseMessage(); Uri resourceUri; if (!Uri.TryCreate(phpAddress.Trim(), UriKind.Absolute, out resourceUri)) { return; } if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https") { return; } // ---------- end of test--------------------------------------------------------------------- string responseText; try { response = await httpClient.GetAsync(resourceUri); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { // Need to convert int HResult to hex string responseText = "Error = " + ex.HResult.ToString("X") + " Message: " + ex.Message; return; } string jsonString = responseText.ToString(); newsItems = DataElements(jsonString); SharedInformation share = SharedInformation.getInstance(); share.setNewsData(newsItems); }
private static async Task EnsureSuccessStatusCode (HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { string responseMessage = null; try { using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (var reader = new StreamReader (responseStream, Encoding.UTF8)) { responseMessage = reader.ReadToEnd(); } } } catch (Exception x) { s_logger.Error ("Exception while trying to read the error message.", x); // throw default exception, if reading the response fails response.EnsureSuccessStatusCode(); } throw new HttpRequestException ( string.Format ( "Response status code does not indicate success: '{0}' ('{1}'). Message:\r\n{2}", (int) response.StatusCode, response.StatusCode, responseMessage)); } }
private async Task TryPostJsonAsync() { try { // Construct the HttpClient and Uri. This endpoint is for test purposes only. //var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); //myFilter.AllowUI = false; //Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); //Windows.Storage.StorageFolder storageFolder = KnownFolders.DocumentsLibrary; fileOpenPicker.FileTypeFilter.Add(".json"); /*fileOpenPicker.FileTypeFilter.Add(".txt"); * Windows.Storage.StorageFile credentialsFile = await fileOpenPicker.PickSingleFileAsync(); * string text = await Windows.Storage.FileIO.ReadTextAsync(credentialsFile); * string username = text.Split(',')[0]; * string password = text.Split(',')[1]; * string domain = text.Split(',')[2];*/ HttpClientHandler handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("", "", ""); System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); Uri uri = new Uri("https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json"); // Construct the JSON to post. //fileOpenPicker.FileTypeChoices.Add("JSON", new List<string>() { ".json" }); IStorageFile jsonFile = await fileOpenPicker.PickSingleFileAsync(); IRandomAccessStream stream = await jsonFile.OpenAsync(FileAccessMode.Read); System.Net.Http.MultipartFormDataContent postContent = new MultipartFormDataContent(); if (stream != null) { using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)stream.Size); string jsonText = dataReader.ReadString(numBytesLoaded); System.Net.Http.StringContent streamContent = new System.Net.Http.StringContent(jsonText); streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); postContent.Add(streamContent); System.Net.Http.HttpResponseMessage httpResponseMessage = await httpClient.PostAsync( "https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json", postContent); // Make sure the post succeeded, and write out the response. httpResponseMessage.EnsureSuccessStatusCode(); var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync(); Debug.WriteLine(httpResponseBody); } } else { Debug.WriteLine("stream is NULL."); } //HttpStringContent content = await jsonFile.OpenReadAsync(); // Post the JSON and wait for a response. } catch (Exception ex) { // Write out any exceptions. Debug.WriteLine(ex); } }