使用 HttpWebRequest 提交附件
本文关键字:提交 HttpWebRequest 使用 | 更新日期: 2023-09-27 18:34:28
>我正在尝试向 REST API 提交附件。 附件未正确提交。我相信我对请求做错了什么
RunQueryimage("http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg);
public string RunQueryimage(string imagePath)
{
//do get request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://iss.ontimenow.com/api/v2/incidents/");
request.ContentType = "application/octet-stream";
request.Method = "POST";
var webClient = new WebClient();
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return result;
}
创建 Web 请求时,您已经打开了一个流。
更改此设置:
byte[] bytearr = webClient.DownloadData(imagePath);
var filecontent = new ByteArrayContent(bytearr);
// request.ContentLength = 0;
if (filecontent != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(filecontent);
}
}
自:
byte[] fileContent = webClient.DownloadData(imagePath);
if (fileContent != null)
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContent, 0, fileContent.Length);
requestStream.Close();
}