How to use verb GET with WebClient request?
Asked Answered
C

4

32

How might I change the verb of a WebClient request? It seems to only allow/default to POST, even in the case of DownloadString.

        try
        {
            WebClient client = new WebClient();               
            client.QueryString.Add("apiKey", TRANSCODE_KEY);
            client.QueryString.Add("taskId", taskId);
            string response = client.DownloadString(TRANSCODE_URI + "task");                
            result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(response);
        }
        catch (Exception ex )
        {
            result = null;
            error = ex.Message + " " + ex.InnerException;
        }

And Fiddler says:

POST http://someservice?apikey=20130701-234126753-X7384&taskId=20130701-234126753-258877330210884 HTTP/1.1
Content-Length: 0
Cultivate answered 2/7, 2013 at 0:38 Comment(4)
You are doing something very special somewhere - DownloadString uses GET: "...For an HTTP resource, the GET method is used".Schrimsher
Strange, I figured "Download" methods would use GET. That is the entirety of my code for this request.Cultivate
Are you completely sure WebClient is not a custom class?Schrimsher
msdn.microsoft.com/en-us/library/system.net.webclient.aspx Yes. I figured Upload<type> methods would use POST or PUT and Download<type> would use GET. Strange. Nowhere else do i override WebClient or extend it.Cultivate
K
44

If you use HttpWebRequest instead you would get more control of the call. You can change the REST verb by the Method property (default is GET)

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(HostURI);
request.Method = "GET";
String test = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    test = reader.ReadToEnd();
    reader.Close();
    dataStream.Close();
 }
 DeserializeObject(test ...)
Keratoplasty answered 2/7, 2013 at 9:32 Comment(3)
This would work. I'm just curious why WebClient in this case uses POST even for Download<object>Cultivate
do you really have to close reader and datastream inside the using?Dampen
This answer is now obsolete check - https://mcmap.net/q/449841/-how-to-use-verb-get-with-webclient-requestHickie
W
3

Not sure if you can use WebClient for that. But why not use HttpClient.GetAsync Method (String) http://msdn.microsoft.com/en-us/library/hh158944.aspx

Weld answered 2/7, 2013 at 0:41 Comment(1)
hm. I want to block the caller and not use Asynchronous request. Another odd thing is HttpClient is not under namespace System.Net.Http in my 4.5 project, in fact System.Net.Http does not exist.Cultivate
M
1

As one can see in the source code of .NET, the HTTP Method of the DownloadString depends on the state of the private WebClient instance field m_Method, which is cleared to null upon each new request method call (link) and defaults to the Web request Creator (depends on the URI, for example ftp protocol gets another creator), but this is not thread safe.

Perhaps you are sharing this WebClient instance among several calls simultaneously?

So it gets confused. Either this or the URI confuses the WebRequest creator.

Marketing answered 24/8, 2017 at 19:44 Comment(0)
H
0

The selected answer is now obsolete, here is a modern example using .NET CORE

Http requests are typically run in Asynchronous way and exceptions needs to be handled

namespace GetConsole
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            var url = "https://cat-fact.herokuapp.com/facts/";
            ApiResponse apiResponse = getData(url).GetAwaiter().GetResult();

            Console.WriteLine(apiResponse.Data);
        }

        static async Task<ApiResponse> getData(string getEndpoint)
        {
            ApiResponse apiResponse = new ApiResponse();

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync(getEndpoint);

                    apiResponse.IsSuccess = response.IsSuccessStatusCode;

                    if (apiResponse.IsSuccess)
                    {
                         apiResponse.Data = await response.Content.ReadAsStringAsync();
                    }
                } 
                catch (Exception ex)
                {
                    apiResponse.IsSuccess = false;
                }
            }


            return apiResponse;
        }
    }
}

class ApiResponse
{
    public bool IsSuccess { get; set; }

    public string Data { get; set; }
}
  

Hickie answered 16/2, 2024 at 13:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.