通过httpwebrequest将附加文件发布到Web服务

时间:2013-07-23 08:14:42

标签: c# web-services post httpwebrequest

我目前正在尝试将xml文件发布到网络服务。

这是我目前的代码

 var tempFileLocation = @"c:\Temp\";             

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(item);
            xdoc.Save(tempFileLocation + "\\pcf.xml");

            var url = "https://Siteaddress/xml.aspx";

            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byte1 = encoding.GetBytes(xdoc.InnerXml);
            HttpWebRequest submissionRequest = (HttpWebRequest)WebRequest.Create(url);
            submissionRequest.KeepAlive = true;
            submissionRequest.Method = "POST";
            submissionRequest.ContentType = "multipart/form-data";
            submissionRequest.ContentLength = byte1.Length;
            submissionRequest.Timeout = 10000;
            submissionRequest.Headers.Add("Accept-Encoding", "gzip,deflate"); 

            Stream requestStream = submissionRequest.GetRequestStream();
            requestStream.Write(byte1, 0, byte1.Length);
            requestStream.Close();

            XmlDocument responseXMLDocument = new XmlDocument();

            HttpWebResponse submissionAcknowledgement = (HttpWebResponse)submissionRequest.GetResponse();

            if (submissionAcknowledgement.StatusCode == HttpStatusCode.OK)
            {
                responseXMLDocument.Load(submissionAcknowledgement.GetResponseStream());

            }

然后我收到以下消息。

错误的Request.Form [pcfxml] - 这应该作为POST附加

我应该如何将xml文件作为附件发布?

2 个答案:

答案 0 :(得分:0)

似乎缺少边界。需要为所有分段上传设置边界...

boundary = GetBoundary();

request.ContentType = "multipart/form-data; boundary=" + boundary;

和边界应如下所示。请注意,每当您在请求流中写入一个字节时,请确保您已提到边界。

private static string GetBoundary()
{
    return "--------------------" + DateTime.Now.Ticks.ToString("x");
}

答案 1 :(得分:0)

最终我找到了一个通过WebClient传递NameValueCollection所需的解决方案

var url = string.Format("https://Site-Address/xml.aspx");

        NameValueCollection nvc = new NameValueCollection();
        nvc.Add("pcfxml", productSerialized);

        WebClient wc = new WebClient();
        var response = wc.UploadValues(url, nvc);

感谢Aundy的回应,我曾经玩过边界。