简体   繁体   中英

How to use verb GET with WebClient request?

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

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 ...)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM