发出 Post 请求时为 WebClient 设置正文 [英] Set a body for WebClient when making a Post Request
问题描述
所以我有一个我想调用的 api.第一个调用是 ahoy 调用,在请求正文中,我需要发送 ship_type、piratename 和我的海盗通行证.然后我想阅读包含我稍后会使用的宝藏的回复.
So I have an api that I want to call to. The first call is an ahoy call and in the body of the request I need to send the ship_type, piratename and my piratepass. I then want to read the response which has my treasure booty that i will use for later.
我可以通过网络请求来做到这一点.但我觉得用 webclient 有更好的方法来做到这一点.
I'm able to do this with web request. but i feel like there is a better way to do it with webclient.
(我目前在 webrequest 中这样做的方式)
(way I currently do it in webrequest)
//Credentials for the Pirate api
string piratename = "IvanTheTerrible";
string piratepass= "YARRRRRRRR";
string URI = "https://www.PiratesSuperSecretHQ.com/sandyShores/api/respectmyauthority";
WebRequest wr = WebRequest.Create(URI);
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
string bodyData = "ship_type=BattleCruiser&piratename=" + piratename + "&piratepass=" + piratepass;
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] byte1 = encoder.GetBytes(bodyData);
wr.ContentLength = byte1.Length;
//writes the body to the request
Stream newStream = wr.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
WebResponse wrep = wr.GetResponse();
string result;
using (var reader = new StreamReader(wrep.GetResponseStream()))
{
result = reader.ReadToEnd(); // do something fun...
}
提前致谢.
推荐答案
你可以用这个简单的代码
You can do with this simple code
Uri uri = new Uri("yourUri");
string data = "yourData";
WebClient client = new WebClient();
var result = client.UploadString(uri, data);
请记住,如果您想异步,可以使用 UploadStringTaskAsync
Remember that you can use UploadStringTaskAsync if you want to be async
这篇关于发出 Post 请求时为 WebClient 设置正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!