I am new to C#, I need to send HTTP GET request and read answer. I am familiar with Java and easy can do it URLConnection class but I don't know in c#. Can anybody help ?
The simplest way is to use WebClient:
WebClient client = new WebClient();
string text = client.DownloadString(url);
(That's the synchronous form; it also supports asynchronous requests.)
For more control you might want to use HttpWebRequest.
Related
I have website which gives me different value (example: value="c04f8d84708f9865f4e04802c51c2f90") every time when I clear cookies in my standard browsers (Firefox, Chrome...).
But when I use client I get always same value, my code:
WebClient client1 = new WebClient();
client1.Headers.Add("Cache-Control", "no-cache");
client1.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
string html = client1.DownloadString("website");
client1.Dispose();
How I can clear all data/cookies so I can get different value ?
Have you tried this:
httpClient.DefaultRequestHeaders.Accept.Clear();
use HttpRequest object instead of WebClient, and hopefully (if you place your doubts in WebClient) everything will be solved. If it wasn't solved with HttpRequest, then the problem really IS somewhere else.
Hope this helps.
i'm trying to invoke a webapi with the new System.Net.WebClient and didnot found any special examples.
The goal is simulate a traditional form post with some fields and a file.
how can i do it using the System.Net.WebClient or where can i find some examples?
thanks in advance
I think you need this:
http://dzimchuk.net/post/uploading-a-file-over-http-in-net
This is a very well written blog. See the last example.
There are a lot of examples if you do a fast google search, anyway, here goes some samples:
Simple GET
WebClient webClient = new WebClient();
webClient.Headers["Accept"] = "application/json"; //setting headers
string json = webClient.DownloadString(url);
Simple POST
NameValueCollection values = new NameValueCollection();
values["user"] = username;
values["pwd"] = password;
webClient.UploadValues(url, values);
There's also an UploadData that sends byte arrays and UploadFile that allows you to upload files directly from disk.
I have a simple Restful service being called from a console app so am using WebClient. I am wondering if this call for Delete is correct.
The url looks like localhost/RestService1/Person/1
using (var client = new WebClient())
{
client.UploadString(url, "DELETE", "");
}
I don't like that UploadString does not have an overload without a data parameter. The passing of an empty parameter is not sitting well with me. Is there a better method to use for a DELETE?
I could use WebRequest but I want to just use WebClient to keep it consistent.
Here is the WebRequest block
var request = WebRequest.Create(url);
request.Method = "DELETE";
var response = (HttpWebResponse)request.GetResponse();
Both blocks work fine but what is best? Or is there a better way?
The following works for me:
client.UploadValues(url, "DELETE", new NameValueCollection());
The WebClient class doesn't really lend well to restful api consumption, I've used 3rd party libraries like RestSharp in the past that are geared more towards this type of web request. I'm pretty sure RestSharp just uses HttpWebRequest under the covers, but it provides a lot of semantics that make consuming and reusing rest resources easier.
Go get the Microsoft.Net.Http client libraries http://nuget.org/packages/Microsoft.Net.Http
HttpClient is a much better client to use for working with an API.
Sorry this is my solution in vb.net i sure that anyone can translate to c#
It's very important to drop headers, i had to comment header about Accept and Content-Type and work fine..... of course I did send the token
Dim rest As WebClient = New WebClient()
rest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " & Token)
'rest.Headers.Add(HttpRequestHeader.Accept, "application/json")
'rest.Headers.Add(HttpRequestHeader.ContentType, "application/json")
result = System.Text.Encoding.UTF8.GetString(rest.UploadValues(host_api & uri, "DELETE", New NameValueCollection()))
What difference is there between the WebClient and the HttpWebRequest classes in .NET? They both do very similar things. In fact, why weren't they merged into one class (too many methods/variables etc may be one reason but there are other classes in .NET which breaks that rule).
Thanks.
WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:
var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With WebClient, you just do DownloadString:
var client = new WebClient();
var content = client.DownloadString("http://example.com");
Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.
In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.
Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.
Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422
I know its too longtime to reply but just as an information purpose for future readers:
WebRequest
System.Object
System.MarshalByRefObject
System.Net.WebRequest
The WebRequest is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest and FileWebRequest.
You use Create method of WebRequest to create an instance of WebRequest. GetResponseStream returns data stream.
There are also FileWebRequest and FtpWebRequest classes that inherit from WebRequest. Normally, you would use WebRequest to, well, make a request and convert the return to either HttpWebRequest, FileWebRequest or FtpWebRequest, depend on your request. Below is an example:
Example:
var _request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
var _response = (HttpWebResponse)_request.GetResponse();
WebClient
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Net.WebClient
WebClient provides common operations to sending and receiving data from a resource identified by a URI. Simply, it’s a higher-level abstraction of HttpWebRequest. This ‘common operations’ is what differentiate WebClient from HttpWebRequest, as also shown in the sample below:
Example:
var _client = new WebClient();
var _stackContent = _client.DownloadString("http://stackoverflow.com");
There are also DownloadData and DownloadFile operations under WebClient instance. These common operations also simplify code of what we would normally do with HttpWebRequest. Using HttpWebRequest, we have to get the response of our request, instantiate StreamReader to read the response and finally, convert the result to whatever type we expect. With WebClient, we just simply call DownloadData, DownloadFile or DownloadString.
However, keep in mind that WebClient.DownloadString doesn’t consider the encoding of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify an encoding.
NOTE: Basically "WebClient takes few lines of code as compared to WebRequest"
Trying to use RSS.NET. Example on the site is: (C#)
string url = "http://sourceforge.net/export/rss2_sfnews.php?feed";
RssFeed feed = RssFeed.Read(url);
RssChannel channel = (RssChannel)feed.Channels[0];
listBox.DataSource = channel.Items;
However, this fails because I need to access the feed through a proxy. How do I do this?
An overload for RssFeed.Read() takes HttpWebRequest. I think this may be the way of setting this up, but I haven't used this before. Help! :)
You can indeed use the HttpWebRequest overload of the RssFeed.Read() function. The following should work
string url = "http://sourceforge.net/export/rss2_sfnews.php?feed";
string proxyUrl = "http://proxy.example.com:80/";
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
WebProxy proxy = new WebProxy(proxyUrl,true);
webReq.Proxy = proxy;
RssFeed feed = RssFeed.Read(webReq);
If you need a username and password for the proxy there is a more detailed example here.
There is an overload of the RssFeed.Read() method that accepts an HttpWebRequest. You can set the proxy on the HttpWebRequest and read it that way. This sets the proxy for the RSS feed in particular. You would need to do this for each feed you read in.
You can set the default proxy using System.Net.WebRequest.DefaultWebProxy, prior to calling RssFeed.Read(String). Do this just once; it will apply to all Rss feeds you read, as well as all other http communicatious going out from your app.