xml data POST from file - c#

i am trying to send xml data from file to sensor what should get XML and make a values from that. I have this code, but i don't know if it is actually working.
I do have response from server but does it actually get those data from xml file? I am still newbie so i still don't know.
Thank you for any help..
class Program
{
static void Main(string[] args)
{
WebRequest request = WebRequest.Create("http://192.168.254.20:5050/token");
request.Method = "POST";
string postData = #"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
Console.WriteLine(postData);
Console.ReadKey();
reader.Close();
dataStream.Close();
response.Close();
}
}

You need to read your xml file then you can convert it to bytes and then you can post it to server.
byte[] xmlData= File.ReadAllBytes(#"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml");

This is an other approach:
var xmlFile = #"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml";
var client = new HttpClient { BaseAddress = new Uri("http://192.168.254.20:5050/")};
using(var content = new StringContent(File.ReadAllText(xmlFile), Encoding.UTF8, "text/xml"))
{
var result = await client.PostAsync("token", content);
var respnseText = await result.Content.ReadAsStringAsync();
}
(Note: if you are accessing the same service endpoint with the same settings multiple times you can reuse the HttpClient instance to call the different service methods even across threads. This is why I have not wrapped it into a using clause)
If you have difficulties communicating with the service you might have other problems. If you don't get an exception then you can inspect the properties of the result to see if the service endpoint returned success (OK=200) or some other result code. You might find details about it. You could also simply reproduce this code in html+javascript, there you can more easily inspect the traffic in the browser. Of course, you could use some network sniffer, but that can be far more complicated.
[Update]
If you really only need to pass the file name as GET parameter, then use something like this:
var xmlFile = #"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml";
var uri = new Uri($"http://192.168.254.20:5050/token?content={xmlFile}", UriKind.Absolute);
using (var client = new HttpClient())
{
var result = await client.GetAsync(uri);
var respnseText = await result.Content.ReadAsStringAsync();
}

Related

c# HTTP PATCH 400 error

I am currently working on implementing a class for accessing rest webservices with my C# program. I managed to do that for PUT, Post and GET, but I have problems with the Patch. The following error occurs everytime:
There is an exception error “System.Net.WebException” in System.ddll
Additional information: remote server reported: (400) Unvalid request
I have researched and tried out various things – to no avail. I would appreciate any help!
Many thanks in advance
public string WebserviceSenden()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create( GrundURL + ErweiterungsURL);
// Set the Method property of the request to POST.
request.Method = Methode;
// Create POST data and convert it to a byte array.
string postData = DateSenden;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
public string WebserviceEmpfangen()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create(
GrundURL + ErweiterungsURL);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
return responseFromServer;
}
}
private void button1_Click(object sender, EventArgs e)
{
String Jason = "";
RestClient AbfrageStarten = new RestClient();
AbfrageStarten.GrundURL = "URL";
AbfrageStarten.ErweiterungsURL = "540697";
Jason = AbfrageStarten.WebserviceEmpfangen();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<List<Lagereinheit>>(Jason, settings);
KorrekturLagereinheit = list[0];
KorrekturLagereinheit.stueckzahl = 5858;
string Test;
Test = JsonConvert.SerializeObject(KorrekturLagereinheit, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
RestClient AntwortSenden = new RestClient();
AntwortSenden.GrundURL = "URL";
AntwortSenden.ErweiterungsURL = "540697";
AntwortSenden.Methode = "Patch";
AntwortSenden.DateSenden = Test;
AntwortSenden.WebserviceSenden();
}
Error message
Many thanks in advance

Getting content from httpwebresponse exception

My remote server is throwing a web exception as bad request. But I know there is more information included in the error than what I get. If I look at the details from the exception it does not list the actual content of the response. I can see the content-type, content-length and content-encoding only. If I run this same message through another library (such as restsharp) I will see detailed exception information from the remote server. How can I get more details from the response since I know the remote server is sending them?
static string getXMLString(string xmlContent, string url)
{
//string Url;
string sResult;
//Url = ConfigurationManager.AppSettings["UserURl"] + url;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/xml";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(xmlContent);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
sResult = result;
}
}
return sResult;
}
EDIT : Have you tried with a simple try-catch to see if you can get more details ?
try
{
var response = (HttpWebResponse)(request.GetResponse());
}
catch(Exception ex)
{
var response = (HttpWebResponse)ex.Response;
}
In my recherches in an answer for you, I noticed that in code there was something about encoding, that you didn't specified. Look here for exemple with such code.
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
Or here, in the doc, also.
// Creates an HttpWebRequest with the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
Have you tried with such ?

How to post non-standard XML with C#

I have utilities that post standard XML, but am faced with interacting with a server that requires something I'm not familiar with.
The expected XML format is like this:
"xmldata=<txn><element_1>element_1_value</element_1><element_2>element_2_value</element_2></txn>"
When I post using my standard method:
byte[] data = Encoding.ASCII.GetBytes(XDocumentToString(xml));
var client = new WebClient();
client.Headers.Add("Content-Type", "text/xml");
byte[] result = client.UploadData(new Uri(url), "POST", data);
string resultString = Encoding.ASCII.GetString(result);
return XDocument.Parse(resultString);
I get an error message about the XML not being formatted correctly.
When I use some stuff I've found:
var request = _requestFactory.CreateCreditCardSaleRequest(xmlStringFromAbove);
WebRequest webRequest = WebRequest.Create("https://domain.com/process_some_xml.do");
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(request);
// Set the ContentType property of the WebRequest.
webRequest.ContentType = "text/xml; encoding='utf-8'";
// Set the ContentLength property of the WebRequest.
webRequest.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = webRequest.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
// dataStream.Close();
// Get the response.
WebResponse response = webRequest.GetResponse();
// Display the status.
var httpWebResponse = (HttpWebResponse) response;
Console.WriteLine(httpWebResponse.StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
the response seems to indicate success, but no response content as expected.
I suspect it has something to do with the "xmldata=" at the beginning of the request, but cannot be sure.
Any suggestions?
Judging from the xmldata=, it sounds like the API wants the data sent as form-urlencoded. I suggest trying this:
string dataStr = "xmldata=" + HttpUtility.UrlEncode(XDocumentToString(xml));
byte[] data = Encoding.ASCII.GetBytes(dataStr);
and this:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

Getting file returned using FileContentResult and writing it to a file

Right now, I have a web service (.asmx) that calls a mvc 4 controller action returning a PDF file via:
return File(pdfBytes, "application/pdf", "Report.pdf");
And I'm getting the result in the web service like this:
WebResponse response = request.GetResponse();
var status = ((HttpWebResponse)response).StatusDescription;
var dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
What I want is to write the file returned into the file system. Something like this:
byte[] responseBytes = Encoding.UTF8.GetBytes(responseFromServer);
var file = File.Create("C://Report.pdf");
file.Write(responseBytes, 0, responseBytes.Length);
But the file written has all the pages in blank.
What am I missing here?
The solution to this was to get the bytes directly from the response stream.
Like this:
var dataStream = response.GetResponseStream() ;
byte[] responseBytes;
using (var memoryStream = new MemoryStream())
{
dataStream.CopyTo(memoryStream);
responseBytes = memoryStream.ToArray();
return responseBytes;
}
Don't use the WebResponse object for this. Use the WebClient instead. It is great for downloading binary data over http. All you need to do is replace your webservice´s code with:
var serverUrl = "http://localhost:60176/Demo/PdfFile"; //... replace with the request url
var client = new System.Net.WebClient();
var responseBytes = client.DownloadData(serverUrl);
System.IO.File.WriteAllBytes(#"c:\Report.pdf", responseBytes);
Good luck!

Httpwebrequest--POST method using text file

I am trying to replicate a Couch database using .NET classes instead of a curl command line. I have never used WebRequest or Httpwebrequest before, but I am attempting to use them to make a post request with the script below.
Here is the JSON script for couchdb replication(I know this works):
{ ""_id"":"database_replicate8/7/12", "source":sourcedb, ""target"":"targetDB", ""create_target"":true, ""user_ctx"": { ""roles"": ["myrole"] } }
The above script is put into a text file, sourcefile.txt. I want to take this line and put it in a POST web request using .NET functionality.
After looking into it, I chose to use the httpwebrequest class. Below is what I have so far--I got this from http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
HttpWebRequest bob = (HttpWebRequest)WebRequest.Create("sourceDBURL");
bob.Method = "POST";
bob.ContentType = "application/json";
byte[] bytearray = File.ReadAllBytes(#"sourcefile.txt");
Stream datastream = bob.GetRequestStream();
datastream.Write(bytearray, 0, bytearray.Length);
datastream.Close();
Am I going about this correctly? I am relatively new to web technologies and still learning how http calls work.
Here is a method I use for creating POST requests:
private static HttpWebRequest createNewPostRequest(string apikey, string secretkey, string endpoint)
{
HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
request.Proxy = null;
request.Method = "POST";
//Specify the xml/Json content types that are acceptable.
request.ContentType = "application/xml";
request.Accept = "application/xml";
//Attach authorization information
request.Headers.Add("Authorization", apikey);
request.Headers.Add("Secretkey", secretkey);
return request;
}
Within my main method I call it like this:
HttpWebRequest request = createNewPostRequest(apikey, secretkey, endpoint);
and I then pass my data to the method like this:
string requestBody = SerializeToString(requestObj);
byte[] byteStr = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteStr.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteStr, 0, byteStr.Length);
}
//Parse the response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Business error
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(string.Format("Error: response status code is{0}, at time:{1}", response.StatusCode, DateTime.Now.ToString()));
return "error";
}
else if (response.StatusCode == HttpStatusCode.OK)//Success
{
using (Stream respStream = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(SubmitReportResponse));
reportReq = serializer.Deserialize(respStream) as SubmitReportResponse;
}
}
...
In my case I serialize/deserialize my body from a class - you will need to alter this to use your text file. If you want an easy drop in solution, then change the SerializetoString method to a method that loads your text file to a string.

Categories