我正在尝试将一些XML发布到Web服务器。为此,我必须使用HTTP协议,Post方法,multipart / form-data Content-Type,带有1个参数,名为" xmlinfo"包含我上传的XML。服务器使用基本身份验证。
我不断收到以下错误消息:
System.Net.Http.HttpRequestException:发送请求时发生错误---> System.Net.WebException:底层连接已关闭:连接意外关闭。
我不确定为什么会发生这种情况,因为我会在没有问题的情况下向其他服务器发帖;但是,这些帖子不涉及多部分/表单数据内容类型。我正在寻找有关如何绕过它的建议。
以下是我目前在将xml发布到服务器时遇到问题的功能:
public static async Task<Object> SaveXMLAsync(string xml)
{
Object strResult = String.Empty;
using (HttpClientHandler handler = new HttpClientHandler())
{
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = user;
credentials.Password = password;
handler.Credentials = credentials;
using (var webClient = new HttpClient(handler))
{
webClient.BaseAddress = new Uri(ip);
webClient.DefaultRequestHeaders.Accept.Clear();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, String.Format("{0}import/xml", ip)))
{
using (var content = new MultipartFormDataContent("----MyBoundary"))
{
StringContent xmlContent = new StringContent(xml, Encoding.UTF8, "application/xml");
content.Add(xmlContent, "xmlinfo");
request.Content = content;
request.Headers.ExpectContinue = false;
try
{
var response = await webClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None);
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync();
strResult = result.Result;
}
else
{
strResult = string.Format("Problem: {0}", response.RequestMessage);
}
}
catch (Exception ex)
{
strResult = ex.ToString();
}
}
}
}
}
return strResult;
}