HTTP Post: Issue with posting XML with credentials



I need help/ suggestion/ idea/ or similar with Http Post. I'm having issues with posting XML file to URL with credentials. Server that I need to post have two text boxes for username and password and upload button to choose file for uploading/ posting. My code looks like all examples that I've found online: I'm sending credentials as NameValueCollection, content type as multipart/form-data etc. I'm also getting Acknowledgment that file is posted successfully (same acknowledgement I get when post file manually). But, record in database for posted file is missing when I post using my code. I really don`t know what can be the issue, because same method works just fine with other type of XML (one with namespaces, envelopes etc). This file I want to post does not have namespace, just basic structure like this:



<Test>
<TestID>someInfo</TestID>
<Name>someNAme</Name>
</Test>


Does anyone have idea what can be the issue and how can I solve it? Thank you very much in advance.


Here's code I'm using:



public static void HttpPost(string xmlFile, string url, string username, string password)
{
NameValueCollection formData = new NameValueCollection();
string result = null;
formData["Username"] = username;
formData["Password"] = password;

string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);

var request = (HttpWebRequest)(WebRequest.Create(url));

request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Credentials = CredentialCache.DefaultCredentials;

// Ignore Certificate validation failures
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

Encoding encoding = Encoding.UTF8;

try
{
Stream postDataStream = GetPostStream(xmlFile, formData, boundary, encoding);

byte[] bytes = new byte[postDataStream.Length];
postDataStream.Position = 0;
postDataStream.Read(bytes, 0, (int)bytes.Length);

string data = encoding.GetString(bytes);
byte[] byteArray = encoding.GetBytes(data);

webRequest.ContentLength = byteArray.Length;
request.ContentLength = byteArray.Length;

ServicePoint point = request.ServicePoint;
point.ReceiveBufferSize = 2048;
point.ConnectionLeaseTimeout = Timeout.Infinite;
request.ServicePoint.Expect100Continue = false;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();.
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
postDataStream.Close();

}
catch (Exception e)
{
throw new Exception(String.Format("Failed Stream {0}", e.InnerException));
}


GetPostStream Method:



private static Stream GetPostStream(string filepath, NameValueCollection formData, string boundary, Encoding encoding)
{
Stream postDataStream = new System.IO.MemoryStream();

try
{
string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";

foreach (string key in formData.Keys)
{
byte[] formItemBytes = encoding.GetBytes(string.Format(formDataHeaderTemplate,
key, formData[key]));
postDataStream.Write(formItemBytes, 0, formItemBytes.Length);
}
FileInfo fileInfo = new FileInfo(filepath);

string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
Environment.NewLine + "Content-Type: text/xml" + Environment.NewLine + Environment.NewLine;

byte[] fileHeaderBytes = encoding.GetBytes(string.Format(fileHeaderTemplate,
"HTTPPOSTFILE", fileInfo.FullName));

postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);

FileStream fileStream = fileInfo.OpenRead();

byte[] buffer = new byte[fileStream.Length];

int bytesRead = 0;

while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postDataStream.Write(buffer, 0, bytesRead);
}

fileStream.Close();

byte[] endBoundaryBytes = encoding.GetBytes("--" + boundary + "--");
postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

}

catch (Exception e)
{

throw new Exception(e.InnerException.ToString());
}

return postDataStream;
}

No comments:

Post a Comment