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?
Related
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.
I wish to automatically uncompress GZiped response.
I am using the following snippet:
mywebclient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
mywebclient.Encoding = Encoding.UTF8;
try
{
var resp = mywebclient.DownloadData(someUrl);
}
I have checked HttpRequestHeader enum, and there is no option to do this via the Headers
How can I automatically decompress the resp? or Is there another function I should use instead of mywebclient.DownloadData ?
WebClient uses HttpWebRequest under the covers. And HttpWebRequest supports gzip/deflate decompression. See HttpWebRequest AutomaticDecompression property
However, WebClient class does not expose this property directly. So you will have to derive from it to set the property on the underlying HttpWebRequest.
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
Depending on your situation, it may be simpler to do the decompression yourself.
using System.IO.Compression;
using System.Net;
try
{
var client = new WebClient();
client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
var responseStream = new GZipStream(client.OpenRead(myUrl), CompressionMode.Decompress);
var reader = new StreamReader(responseStream);
var textResponse = reader.ReadToEnd();
// do stuff
}
I created all the temporary variables for clarity. This can all be flattened to only client and textResponse.
Or, if simplicity is the goal, you could even do this using ServiceStack.Text by Demis Bellot:
using ServiceStack.Text;
var resp = "some url".GetJsonFromUrl();
(There are other .Get*FromUrl extension methods)
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
I am using GitHub API v3 with C#. I am able to get the access token and using that I am able to get the user information and repo info.
But when I try to create a new repo I am getting the error as Unauthorized.
I am using HttpWebRequest to post data, which can be seen below. Please suggest me some C# sample or sample code.
(..)string[] paramName, string[] paramVal, string json, string accessToken)
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.Write(json);
writer.Close();
string result = null;
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}(..)
Note: I am not sure where i need to add the accesstoken. I have tried in headers as well as in the url, but none of them works.
Are you using the C# Github API example code? I would look at that code to see if it does what you need.
You can use basic auth pretty easily by just adding auth to the request headers:
request.Headers.Add("Authorization","Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username +":"+password)));
Sorry havent used the access token stuff yet.
You need to add this token here:
req.UserAgent = "My App";
req.Headers.Add("Authorization", string.Format("Token {0}", "..token..");
Try
rec.Credentials = CredentialCache.DefaultCredentials;
or use non-default credentials.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.credentials.aspx
I need to connect to a website using a proxy server. I can do this manually, for example I can use the online proxy http://zend2.com and then surf to www.google.com. But this must be done programmatically. I know I can use WebProxy class but how can I write a code so a proxy server can be used?
Anyone can give me a code snippet as example or something?
thanks
Understanding of zend2 works, you can populate an url like this :
http://zend2.com/bro.php?u=http%3A%2F%2Fwww.google.com&b=12&f=norefer
for browsing google.
I C#, build the url like this :
string targetUrl = "http://www.google.com";
string proxyUrlFormat = "http://zend2.com/bro.php?u={0}&b=12&f=norefer";
string actualUrl = string.Format(proxyUrlFormat, HttpUtility.UrlEncode(targetUrl));
// Do something with the proxy-ed url
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(actualUrl));
HttpWebResponse resp = req.GetResponse();
string content = null;
using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
content = sr.ReadToEnd();
}
Console.WriteLine(content);
You can use WebProxy Class
MSDN code
WebProxy proxyObject = new WebProxy("http://proxyserver:80/",true);
WebRequest req = WebRequest.Create("http://www.contoso.com");
req.Proxy = proxyObject;
In your case
WebProxy proxyObject = new WebProxy("http://zend2.com",true);
WebRequest req = WebRequest.Create("www.google.com");
req.Proxy = proxyObject;