gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:28:26 26 4
gpt4 key购买 nike

我正在使用下面的代码来发布具有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);
}
}

最佳答案

与其自行实现,不如考虑使用新的 API:HttpClient类(class)。它有 support对于 multipart/form-data

有关实际示例,请参见例如this answer on another question

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

关于c# - 多部分/表单数据内容类型请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32412562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com