[英]Making a CURL POST request to server in C# HttpWebRequest
I am attempting to make a POST request to a server. 我正在尝试向服务器发出POST请求。 The following works when I CURL using git Bash: 当我使用git Bash进行CURL时,以下方法有效:
curl -X POST -H "Content-Type: application/octet-stream" -H "User-Agent: MyUserAgent" --data-binary @MyDocument.xlsx http://myUrl.com
I know I can make POST requests using json as follows (in C#): 我知道我可以使用json发出POST请求,如下所示(在C#中):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
request.UserAgent = myUserAgent;
using (var stream = await request.GetRequestStreamAsync())
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
streamWriter.Write(myJsonData);
}
}
using (HttpWebResponse webResponse = (HttpWebResponse) await request.GetResponseAsync())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string response = reader.ReadToEnd();
//do stuff with response
}
}
My difficulty is basically combining the two. 我的困难基本上是将两者结合在一起。 I know I need to change the request.ContentType to "application/octet-stream", but that is not enough. 我知道我需要将request.ContentType更改为“ application / octet-stream”,但这还不够。 How do I incorporate the "--data-binary @MyDocument.xlsx" in the HttpWebRequest? 如何在HttpWebRequest中合并“ --data-binary @ MyDocument.xlsx”? Anyone have any ideas? 有人有想法么? Thanks! 谢谢!
I suggest you look into WebClient
since it's easier to implement: 我建议您研究WebClient
因为它更容易实现:
WebClient client = new WebClient();
byte[] response = client.UploadFile(myUrl,fileName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.