我是网络服务的新手 . 我正在尝试将zip文件上传到REST服务,其内容类型和接受标头值为“application / json”(由Web服务指定)

我无法上传文件,因为它正在抛出“远程服务器返回错误:(400)错误请求” .

我尝试传递multipart \ form-data,但它抛出了同样的异常 . 另外,我很困惑,因为我听说对于zip文件我们需要使用“Multipart / form-data”作为内容类型,但是web-server将它指定为“application / json” . 如何以JSON格式发送zip文件?

以下是我使用的代码:

public static async Task<string> LogData()
{
   string bMsg = "";
   try
   {                              
      string loginUrl = "https://example.com/self";
      string refererUrl = "https://example.com";
      string uploadFileURL = "https://example.com/files";

      //Login to the URL(Rest API Endpoint)
      HttpWebRequest request = WebRequest.Create(loginUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";
      request.Referer = refererUrl;
      request.Accept = "application/json";  
      request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));

    //Get the response and check if it is successfully logged in or not 
   HttpWebResponse webResponse = request.GetResponse() as HttpWebResponse;
   string statusMsg = "";
   if (webResponse.StatusCode == HttpStatusCode.OK)
   {
       statusMsg = "OK";
   }
   if (webResponse.StatusCode == HttpStatusCode.Forbidden)
   {
       statusMsg = "Forbidden";         
   }

   //Get "set-cookie" value from the response and use it for file upload
   string cookieString = webResponse.Headers.Get("Set-Cookie");

   // Read file data
   string zipFilepath=@"C:Test.zip";
   FileInfo fInfo = new FileInfo(zipFilepath);
   long numBytes = fInfo.Length;
   FileStream fStream = new FileStream(zipFilepath, FileMode.Open, FileAccess.Read);
   BinaryReader br = new BinaryReader(fStream);
   byte[] bdata = br.ReadBytes((int)numBytes);
   br.Close();
   fStream.Close();

   // Write bdata to the HttpStream
   HttpWebRequest webRequest (HttpWebRequest)WebRequest.Create(uploadFileURL);

  // Additional webRequest parameters settings.
  webRequest.Method = "POST";
  webRequest.ContentType ="application/json";  
  webRequest.Referer = refererUrl;
  webRequest.Accept = "application/json";
  webRequest.Headers.Add("Cookie", cookieString);
  webRequest.ContentLength = bdata.Length;
  Stream stream = (Stream)webRequest.GetRequestStream();
  stream.Write(bdata, 0, bdata.Length);
  stream.Close();

 HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
 StreamReader responseReader = newStreamReader(response.GetResponseStream());
 string fullResponse = responseReader.ReadToEnd();
 response.Close();

 }
 catch (Exception ex)
 {
      bMsg = "Unable to send request";        
 }
 return bMsg;

}