After I upgraded the framework of web app from 4.0 to 4.6 I found that there is no more ReadAsAsync() method in HTTP protocol library, instead of ReadAsAsync() there is GetAsync(). I need to serialize my custom object using GetAsync().
The code using ReadAsAsync():
CustomResponse customResponse = client.ReadAsAsync("api/xxx", new StringContent(new JavaScriptSerializer().Serialize(request), Encoding.UTF8, "application/json")).Result;
Another example based on ReadAsAsync()
CustomResponse customResponse = await Response.Content.ReadAsAsync<CustomResponse>();
How to achieve same goal using GetAsync() method ?
You can use it this way:
(you might want to run it on another thread to avoid waiting for response)
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(page))
{
using (HttpContent content = response.Content)
{
string contentString = await content.ReadAsStringAsync();
var myParsedObject = (MyObject)(new JavaScriptSerializer()).Deserialize(contentString ,typeof(MyObject));
}
}
}
Related
After 2-4 downloading of videos data from API using HttpClient suddenly prompt error.
Here's my code:
public async Task<byte[]> GetMedia(string id)
{
var api = $"/api/v1/download/{id}";
var Uri = $"{MccBaseURL}{api}";
byte[] responseBody;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("No");
try
{
HttpResponseMessage response = await httpClient.GetAsync(Uri);
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsByteArrayAsync();
if (response.IsSuccessStatusCode)
{
return responseBody;
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
throw;
}
}
Then below is the error faced:
Additional error info:
Error
Please help me?
First, you should dispose your HttpResponseMessage, as you have in your answer, but not in the original question.
The most likely issue, though, is your use of DefaultRequestHeaders. You should only use this for headers that apply to every request that the HttpClient instance will send, and then you should set them only once, when you create the client, as the documentation implies ("Headers set on this property don't need to be set on request messages again").
While HttpClient is essentially thread-safe, the DefaultRequestHeaders (and BaseAddress) properties are not. You're changing these values while the client instance is potentially busy using them elsewhere. It's not clear whether you're using the singleton HttpClient elsewhere as well, possibly changing the default headers there too, but if so that would significantly increase the chances of issues arising.
Some additional references about the non-thread-safety of these properties:
https://github.com/dotnet/dotnet-api-docs/issues/1085
http://www.michaeltaylorp3.net/httpclient-is-it-really-thread-safe/
https://github.com/MicrosoftDocs/architecture-center/issues/935
I found an answer which is:
public async Task<bool> GetMedia(string saveDir, string id)
{
var api = $"/api/v1/download/{id}";
var Uri = $"{MccBaseURL}{api}";
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
using (System.IO.Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
string fileToWriteTo = System.IO.Path.GetTempFileName();
using (System.IO.FileStream streamToWriteTo = new System.IO.FileStream(saveDir, System.IO.FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
return true;
}
}
}
}
It was really memory something problem which continuously using same HttpClient over and over again. So I created a new instance. I'm a super noob! Sorry!
import requests
requests.post('https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start',
auth=('john#doe.com', 'secretPassword'))
How would one write this in C#? (NET Core)
Apart of the added comments, I would recommend using a library called RestSharp.
You can easily find the nuget package and the code will be as easier as:
var client = new RestClient("https://dathost.net");
client.Authenticator = new HttpBasicAuthenticator("john#doe.com", "secretPassword");
var request = new RestRequest("api/0.1/game-servers/{id}/start", Method.POST);
request.AddUrlSegment("id", "54f55784ced9b10646653aa9");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;
You can also do async requests:
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
You can do it with HttpClient.
Add usings top of your code first.
using System.Net.Http;
using System.Net.Http.Headers;
And run this code wherever you want.
var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("john#doe.com:secretPassword");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = await client.PostAsync(
"https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start", null);
Hope this helps.
1)
WebRequest request = WebRequest.Create("");
I can not use this method.
The reason is my mono can not load the System.Net.Configuration.WebRequsetModulesSection.
2)
Navigate(bstrURL, &vFlags, &vTargetFrameName, &vPostData, &vHeaders);
I can not use this method.
The reason is can not use the namespace using System.Windows.Forms;
What else can I use to post data to the URL.
You can use HttpClient:
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[0]);
var response = await httpClient.PostAsync("URL", content);
string responseAsString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseAsString);
I'am trying to reach a SOAP API using the HttpClient object. I've searched everywhere but most of the people are using the HttpWebRequest object which is not supported by the DNX Core framework.
Does anyone have a working example of a SOAP request using the HttpClient object?
This image represents a simple request from this API (NuSOAP PHP):
Thank you!
EDIT :
So I was able to call the API with the following code:
Uri uri = new Uri("http://localhost/teek_api/service.php");
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Add("SOAPAction", "http://localhost/teek_api/service.php/ping");
var content = new StringContent("text/xml; charset=utf-8");
using (HttpResponseMessage response = await hc.PostAsync(uri, content))
{
var soapResponse = await response.Content.ReadAsStringAsync();
string value = await response.Content.ReadAsStringAsync();
return value;
}
How can I get the HTML source for a given web address in C#?
You can download files with the WebClient class:
using System.Net;
using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
client.DownloadFile("http://yoursite.com/page.html", #"C:\localfile.html");
// Or you can get the file content without saving it
string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}
Basically:
using System.Net;
using System.Net.Http; // in LINQPad, also add a reference to System.Net.Http.dll
WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
Console.WriteLine(source);
The newest, most recent, up to date answer
This post is really old (it's 7 years old when I answered it), so no one of the other answers used the new and recommended way, which is HttpClient class.
HttpClient is considered the new API and it should replace the old ones (WebClient and WebRequest)
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string pageContent = content.ReadAsStringAsync().Result;
}
}
for more information about how to use the HttpClient class (especially in async cases), you can refer this question
NOTE 1: If you want to use async/await
string url = "page url";
HttpClient client = new HttpClient(); // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string pageContent = await content.ReadAsStringAsync();
}
}
NOTE 2: If use C# 8 features
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string pageContent = await content.ReadAsStringAsync();
You can get the HTML source with:
var html = new System.Net.WebClient().DownloadString(siteUrl)
#cms way is the more recent, suggested in MS website, but I had a hard problem to solve, with both method posted here, now I post the solution for all!
problem:
if you use an url like this: www.somesite.it/?p=1500 in some case you get an internal server error (500),
although in web browser this www.somesite.it/?p=1500 perfectly work.
solution:
you have to move out parameters, working code is:
using System.Net;
//...
using (WebClient client = new WebClient ())
{
client.QueryString.Add("p", "1500"); //add parameters
string htmlCode = client.DownloadString("www.somesite.it");
//...
}
here official documentation