我需要在我的应用中获取帮助,因此我想在此api网址上发布一些数据: http://myapiurl.com/myapi/csos.asp?username=asddte&password=erts2&intResortID=7&strpartysurname=test&strpartyfirstname=test&strpartyprefix=M&intqtyadults=1&intqtytotal=1&dtmLine1=20-Mar-2019&strRoomType1=sea&intRooms1=1&intnights1=1&strFlightNo=w&strNotes=FlighDJ76提供BreakfastHoneymooners&strBookingCode = zx&strPosBookingRef = mine&strPromotionCode = hellogirl @ id = 22
有人可以协助我使用什么C#代码
当我在浏览器上放置上面的apiurl时,它将向db插入数据并重新给我运行ID,因此在以c#开发的我的应用中,我该如何执行此操作以发布数据或简单地将其执行”
var request = (HttpWebRequest)WebRequest.Create("http://myapiurl.com/myapi/csos.asp?username=asddte&password=erts2&intResortID=7&strpartysurname=test&strpartyfirstname=test&strpartyprefix=M&intqtyadults=1&intqtyto");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
我可以使用上面的代码吗,因为所有需要发布的数据都包含在网址中。
答案 0 :(得分:0)
您可以使用 HttpClient
在以下版本中可用:.NET Framework 4.5 + 、. NET Standard 1.1 + 、. NET Core 1.0 +。
在C#中,您可以通过 NuGet
来获取它包括:
使用System.Net.Http;
实际上,建议您为应用程序的生命周期创建一个HttpClient实例并进行共享。像这样:
私有静态只读HttpClient客户端=新的HttpClient();
最后,您可以通过HttpClient中的 PostAsync 方法发送POST请求:
var值=新字典{{“ parameter1”, “ value1”},{“ parameter2”,“ value2”}};
var content = new FormUrlEncodedContent(values);
var response =等待 client.PostAsync(“ http://myapiurl.com/myapi/csos.asp”,content);
var responseString =等待响应。Content.ReadAsStringAsync();
例如,如果您的api返回字符串或json,则会得到一个字符串。
这是将POST请求发送到Api的多种方法之一。 您还可以使用:
WebClient
答案 1 :(得分:0)
感谢我已经成功实现了自己想做的事情。下面是最终代码:
var request = (HttpWebRequest)WebRequest.Create("http://myapiurl.com/myapi/csos.asp");
var postData = "username=fdgfdg";
postData += "&password=dfgdg";
postData += "&intResortID=353453";
postData += "&strpartysurname=test";
postData += "&strpartyfirstname=test";
postData += "&strpartyprefix=M";
postData += "&intqtyadults=1";
postData += "&intqtytotal=1";
postData += "&dtmLine1=20-Mar-2019";
postData += "&strRoomType1=sea";
postData += "&intRooms1=1";
postData += "&intnights1=1";
postData += "&strFlightNo=w";
postData += "&strNotes=FlighDJ76";
postData += "&strBookingCode=zx";
postData += "&strPosBookingRef=mine";
postData += "&strPromotionCode=hellogirl";
postData += "&BookID=hgjghjg";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
using (var stream2 = request.GetRequestStream())
{
stream2.Write(data, 0, data.Length);
}
var responser = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(responser.GetResponseStream()).ReadToEnd();
this.WriteToFile("Some data has been posted " +responseString);
我正在使用Visual Studio 2008,因此无法使用Httpclient。但是上面的代码可以正常工作,并且可以帮助我实现所需的目标