2015-09-05 75 views
1

我使用下面的代碼發佈與multipart/form-data內容類型的請求,但得到的異常:的multipart/form-data的內容類型的請求

The remote server returned an error: (532).

我怎樣才能解決這個問題?

public void request222(string cgid) 
{ 
    NameValueCollection nvc = new NameValueCollection(); 
    nvc.Add("action:WebManager", "OK"); 
    nvc.Add("cg_id", "" + cgid + ""); 

    var boundary = "---------------------------DateTime.Now.Ticks.ToString("x")"; 

    //creating request 
    var wr = (HttpWebRequest)WebRequest.Create("http://189.126.121.79:8093/API/CCG"); 
    wr.ContentType = "multipart/form-data; boundary=" + boundary; 
    wr.Method = "POST"; 
    wr.KeepAlive = true; 

    //sending request 
    using (var requestStream = wr.GetRequestStream()) 
    { 
     using (var requestWriter = new StreamWriter(requestStream, Encoding.UTF8)) 
     { 
      //params 
      const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; 
      foreach (string key in nvc.Keys) 
      { 
       requestWriter.Write(boundary); 

       requestWriter.Write(String.Format(formdataTemplate, key, nvc[key])); 
      } 
      requestWriter.Write("\r\n--" + boundary + "--\r\n"); 
     } 
    } 

    //reading response 
    try 
    { 

     using (var wresp = (HttpWebResponse)wr.GetResponse()) 
     { 
      if (wresp.StatusCode == HttpStatusCode.OK) 
      { 
       using (var responseStream = wresp.GetResponseStream()) 
       { 
        if (responseStream == null) 

        using (var responseReader = new StreamReader(responseStream)) 
        { 
         string s= responseReader.ReadToEnd(); 
        } 
       } 
      } 

      throw new ApplicationException("Error Server status code: " + wresp.StatusCode.ToString()); 
     } 
    } 
    catch (Exception ex) 
    { 
     throw new ApplicationException("Error while uploading file", ex); 
    } 
} 
+0

這是一個服務器錯誤,那麼你的要求是任何文件可能無效。無論這是因爲它的語義錯誤的HTTP還是根據API的錯誤請求消息都是你可以弄明白的。 – CodeCaster

回答

0

而是然後實現它你自己,考慮使用新的API,而不是:在HttpClient類。它有supportmultipart/form-data

作爲一個實際例子,參見例如, this answer on another question

而且,它可能是最好只用application/x-www-form-urlencoded代替,因爲你沒有在您的要求發佈(至少在你提供的例子)

+0

嘗試了一個Http客戶端,但得到了連接錯誤: HttpClient c = new HttpClient(); var formData = new FormUrlEncodedContent(new [] { new KeyValuePair (「action:WebManager」,「OK」), new KeyValuePair (「cg_id」,cgid)}); MultipartContent content = new MultipartContent(); content.Add(formData); var result = c.PostAsync(「http://189.126.121.79:8093/API/CCG」,content).Result; – suri

+0

您不應該將'FormUrlEncodedContent'與'MultipartContent'混合。請參閱示例:http://stackoverflow.com/a/15176685/332528 – torvin

相關問題