I am using the below code to post the request with multipart/form-data
content type but got the exception:
The remote server returned an error: (532).
How I can solve this?
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);
}
}
Rather then implementing it on your own, consider using the new API instead: the HttpClient
class. It has support for multipart/form-data
.
For a practical example, see eg this answer on another question
Also, it might be better to just use application/x-www-form-urlencoded
instead, since you don't have any files posted in your request (at least in the example you provided)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.