WebRequest req = WebRequest.Create("[URL here]");
WebResponse rep = req.GetResponse();
I wanted some insights into the relevance of the GetResponse method, it appears to deprecated now.
This other method I hacked together gets the job done.
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(String.Format("http://mywebservicehere/dostuff?url=https://www.website.com"));
request.Method = "GET";
using (var response = (HttpWebResponse) (await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
var encoding = ASCIIEncoding.ASCII;
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
}
Wanted to know of any alternative methods others may have used? Thanks for the help!
I wanted some insights into the relevance of the GetResponse method,
it appears to deprecated now.
It is not deprecated, in the .NET for UWP, is is an async method.
WebRequest req = WebRequest.Create("[URL here]");
WebResponse rep = await req.GetResponseAsync();
Wanted to know of any alternative methods others may have used?
Besides the WebRequest class, there are another 2 HttpClient classes in the Windows Runtime Platform you can use to get a http response.
var client1 = new System.Net.Http.HttpClient();
var client2 = new Windows.Web.Http.HttpClient();
The System.Net.Http.HttpClient is in the .NET for UWP.
The Windows.Web.Http.HttpClient is in the Windows Runtime.
Related
I upgraded my .NET application from the version NET5 to NET6 and placed with a warning that the WebRequest class was obsolete. I've looked at a few examples online, but using HttpClient doesn't automatically grab credentials like WebRequest does, as you need to insert them into a string manually.
How would I convert this using the HttpClient class or similar?
string url = "website.com";
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
StreamReader sr = new(hwr.GetResponseStream());
sr.Close();
hwr.Close();
Have you tried the following?
var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
var response = await myClient.GetAsync("website.com");
var streamResponse = await response.Content.ReadAsStreamAsync();
more info around credentials: How to get HttpClient to pass credentials along with the request?
I spent all day trying to figure out what I was doing wrong yesterday.
Coming here to try and find some help.
The follow error is triggered when I run the actual GetResponse.
I am new to APIs so I am sure I am missing something real simple.
You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.
Here is my code I am using to try and send JSON to the API. Payment object just has the form values entered in and the credentials to use the correct account on the merchants end.
var json = JsonConvert.SerializeObject(payment);
var apiUrl = new Uri($"Removed endpoint URL");
var postBytes = Encoding.UTF8.GetBytes(json);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = postBytes.Length;
httpWebRequest.AllowWriteStreamBuffering = false;
//This is where the error triggers and drops to the catch.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I appreciate any help in advance, I may be doing this completely wrong, its a series of things I threw together trying to fix issues with the call.
Unless I missed it, you're not actually writing your payload data to the HttpWebRequest body before you're sending it.
using (Stream _reqStrm = httpWebRequest.GetRequestStream())
{
_reqStrm.Write(postBytes, 0, postBytes.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
....
Unrelated but if you can, consider HttpClient
Hth..
Can someone help me with following API connection with C#. Never done any API connections before so i am a little unsure how it work. This is for a universal windows application so it will be using c# and XMAL.
Is it possible to do the following PHP API call below using C#:
<?php
$uri = 'http://api.football-data.org/v1/soccerseasons/354/fixtures/?matchday=22';
$reqPrefs['http']['method'] = 'GET';
$reqPrefs['http']['header'] = 'X-Auth-Token: YOUR_TOKEN';
$stream_context = stream_context_create($reqPrefs);
$response = file_get_contents($uri, false, $stream_context);
$fixtures = json_decode($response);
?>
Basically all i need to know is if it is even possible.
Thanks in advance.
It can be something like this (result is as text but you can json too):
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://api.football-data.org/v1/soccerseasons/354/fixtures/?matchday=22");
request.Headers.Add("AUTHORIZATION", "Basic YTph");
request.ContentType = "text/html";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string ResultAsText = stream.ReadToEnd().ToString();
Here is my favorite example of calling a WEB API: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
It shows how to use HttpClient, uses async / await and introduces Formatters.
I have the following Silverlight code. It uploads a file (postData) to a backend through the given url (url).
public async Task<HttpFileUploadResponse> PostFile(string url, byte[] postData, string fileName, bool isPDF) {
HttpWebRequest request = null;
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "multipart/form-data";
using (Stream writeStream = await request.GetRequestStreamAsync()) {
await writeStream.WriteAsync(postData, 0, postData.Length);
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8)) {
return ParseServerResponse(await readStream.ReadToEndAsync());
}
}
The problem with this method is that is freezing Internet Explorer when the line await request.GetRequestStreamAsync() is reached.
Although similar questions have been resolved, such as:
Application hangs on GetRequestStream() after first request
Why does HttpWebRequest.GetResponse() hang when trying to update an OData service?
I've followed the suggested steps, like setting the ContentLength, but the result is the same.
Also I've tried to change the URL to another one corresponding to another backend that is currently working with other Silverlight components that we have. These components also have an await request.GetRequestStreamAsync() but they are working perfectly.
I've tried to change the contentType. My workmates have used Fiddler to see the request but apparently nothing is being sent (I suppose it's because it freezes).
Any idea about what's happening here?
EDIT:
I have decompiled the AsynCompatLibExtensions.cs and TaskExtensions.cs to copy the GetRequestStreamAsync code in order to have a custom cloned class with logs among the instructions.
I have recompiled the solution using this class and the strange thing is that I'm not seeing any log. So I suppose it's freezing when it enters GetRequestStreamAsync but before it reaches any code line inside.
Any idea?
there's a tutorial that actually works for Windows 8 platform with XAML and C#: http://www.tech-recipes.com/rx/1954/get_web_page_contents_in_code_with_csharp/
Here's how:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
However in Windows 8, the last 2 lines which are code to close the connection (I assume), detected error. It works fine without closing the connection, though, but what are the odds? Why do we have to close the connection? What could go wrong if I don't? What do "closing connection" even mean?
If you are developing for Windows 8, you should consider using asynchronous methods to provide for a better user experience and it is the recommend new standard. Your code would then look like:
public async Task<string> MakeWebRequest(string url)
{
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
Maybe they've deprecated close() in the latest API. This should work:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
using(WebResponse myResponse = myRequest.GetResponse() )
{
using(StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
{
string result = sr.ReadToEnd();
}
}
The using command will automatically dispose your objects.
To highlight webnoob's comment:
Just to point out (for OP reference) you can only use using on classes that implement IDisposable (which in this case is fine)
using System.Net;
using System.Net.Http;
var httpClient = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, targetURL);
//message.Headers.Add(....);
//message.Headers.Add(....);
var response = await httpClient.SendAsync(message);
if (response.StatusCode == HttpStatusCode.OK)
{
//HTTP 200 OK
var requestResultString = await response.Content.ReadAsStringAsync();
}
I would recommend using the HTTP Client
s. Microsoft HTTP Client Example