1

I am writing http post method which should have request header with next values

authkey : "somevalue", 
number : "somenumber", 
entity : "someentity". 

Also customer ask me to upload xml file as form data. I am not sure I know how to do this. The following code shows what I have implemented for now:

var req = new HttpRequestMessage(HttpMethod.Post, destinationUrl);
req.Headers.Add("authKey", "somevalue");
req.Headers.Add("number", somenumber);
req.Headers.Add("entity", "someentity");

How can I add my XML? I have found the following code already but not sure it can work for this case :

byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(serverResponse);
req.ContentType = "text/xml; encoding='utf-8'";
req.ContentLength = bytes.Length;
req.Method = "POST";
Stream requestStream = req.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse resp;
ekad
  • 14,436
  • 26
  • 44
  • 46
  • 1
    `but not sure it can work for this case` why can't you just try and see if it woks? – Renatas M. Sep 04 '18 at 11:23
  • So how we should know that? If you at least tried to search and check what is 500 error...here I did it for you: [500 Internal Server Error When sending web request using api](https://stackoverflow.com/questions/18713666/500-internal-server-error-when-sending-web-request-using-api). What I can say from your shared details is..you sent some sort of request, something went wrong while processing your request on server side and you've got 500 as a response. What happened - no one except you can know that. Please read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Renatas M. Sep 04 '18 at 11:32

1 Answers1

0

This looks to have been answered before here... https://stackoverflow.com/a/17535912/3585339

The part you are missing is reading the response into the resp variable you have created like this:

resp = (HttpWebResponse)request.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK)
{
    Stream responseStream = resp.GetResponseStream();
    string responseString = new StreamReader(responseStream).ReadToEnd();
    return responseString;
}
Dafrapster
  • 90
  • 5