多部分/表单-数据内容类型请求

本文关键字:类型 请求 数据 表单 多部 | 更新日期: 2023-09-27 18:11:31

我使用下面的代码发布与multipart/form-data内容类型的请求,但得到了例外:

远程服务器返回错误:(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);
    }
}

多部分/表单-数据内容类型请求

与其自己实现它,不如考虑使用新的API: HttpClient类。支持multipart/form-data

作为一个实际的例子,参见以下对另一个问题的回答

另外,使用application/x-www-form-urlencoded可能更好,因为您的请求中没有发布任何文件(至少在您提供的示例中)