0

我正在尝试向 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;


        }
4

1 回答 1

2

创建 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();
        }
于 2013-10-09T09:05:39.287 回答