C# REST client sending data using POST

后端 未结 1 1960
心在旅途
心在旅途 2021-01-12 05:05

I\'m trying to send a simple POST request to a REST web service and print the response (code is below, mostly taken from Yahoo! developer documentation and the MSDN code sni

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 06:00

    Eventually found the HttpWebRequest.PreAuthenticate property which seems to solve the problem if the code is edited like so:

    request = (HttpWebRequest) WebRequest.Create(uri);
    request.PreAuthenticate = true;
    request.Credentials = new NetworkCredential(user, password);
    request.Method = WebRequestMethods.Http.Post;
    

    From the documentation I presume this forces authentication before the actual POST request is sent. I'm not sure why the class doesn't do this automatically (libraries for other languages make this process transparent, unless you explicitly turn it off), but it has solved the problem for me and may save someone else another 2 days of searching and hair-pulling.

    For what it's worth, PreAuthenticate doesn't need to be set for GET requests, only POST, although if you do set it for a GET request everything will still work, but take slightly longer.

    0 讨论(0)
提交回复
热议问题