2013-10-09 69 views
0

我正在嘗試將附件提交給REST API。附件未正確提交。我相信我做錯了請求使用HttpWebRequest提交附件

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; 


     } 
+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(); 
     }