I am currently trying to retrieve a xml response and parse the result from a web service, but I have ran into issues when receiving the response as a stream and using stream reader to read the result and convert the xml response to a string so it can be parsed to get a result later.
When testing I receive an error that there is illegal characters in path, as the stream reader only accepts a file path not the actual xml response object itself. After extensive searching most of the similar posts on here, most people point to either textreaders or xmlreaders but as the HttpWebResponse returns a stream I can't use those. Does anyone have a idea's or pointers to help me overcome this?
I have included a snippet of the code to how I am handling the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string soapResult = responseStream.ReadToEnd();
Here is the code for the request, just in case it helps.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Location);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytesToWrite = encoding.GetBytes(xml.ToString());
request.Method = "POST";
request.ContentLength = bytesToWrite.Length;
request.ContentType = "application/soap+xml; charset=UTF-8";
Stream newStream = request.GetRequestStream();
newStream.Write(bytesToWrite, 0, bytesToWrite.Length);
newStream.Close();
Thanks
Related
Trying to send a web request with some body content. The important part is that I need some data in the body of the post request. My understanding of how to do this is to open a WebRequestStream, and then write the bytes to it, then to close it. This is supposed to be simple. Here is my code:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create("http://localhost:50203/api/Values");//
request.Method = "POST";
byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
Stream requestBodyStream = request.GetRequestStream();
requestBodyStream.Write(requestBody, 0, requestBody.Length);
requestBodyStream.Flush();
requestBodyStream.Close();
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
myString = reader.ReadToEnd();
But the RequestBodyStream.Write method is not sending anything in the body. I know this because I'm running the server side program at the other end.
I also tried to do this with a StreamWriter instead of using a byte stream, and I get the same result. No matter how I do it, there is no content in the body.
My understanding is that closing the stream is what sends the actual data. I also tried adding a Flush() method to the stream.
Why is this method not producing any body?
Add 'ContentType' and 'ContentLength' headers to the request instance:
request.ContentType = "application/json"; // Or whatever you want
request.ContentLength = requestBody.Length;
HI I have been trying to post data to PHP webservice(3rd party) from my C# code.
The PHP webservice says it expects a parameter c (missing parameter c is the error I get).
I am using JSON to send the data, but i do not understand how do give the parameter. Would be great if some one could throw light on this.The following is my code:
DropYa d = new DropYa();
List<DropYaUser> d1 = new List<DropYaUser>();
DropYaUser ds = new DropYaUser();
ds.action = "create";
ds.groupid = 10;
ds.name = "Test";
ds.manager_key = "test";
d1.Add(ds);
WebRequest request = WebRequest.Create(" http://dev.dropya.net/api/Group.php");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
JavaScriptSerializer ser = new JavaScriptSerializer();//typeof(DropYaUser));
string postData = ser.Serialize(ds);
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();
Console.Write("Wrote");
Console.Read();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Console.Read();
dataStream = response.GetResponseStream();
Console.Read();
// 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();
Console.Read();
response.Close();
Any post request is going to be read as a data stream. The field names and values for a posted form will appear in the stream in a form like "c=ABC&d=123", where 'c' and 'd' are form fields. Of course you can post without any form field names but in this case it is expecting 'c'. What you'll want to do is prepend "c=" to the data you're posting. Perhaps modify your GetBytes line like so:
byte[] byteArray = Encoding.UTF8.GetBytes("c=" + postData);
I am trying to send base64 encoded data through C# WebRequest to php script. Then I receive sent data by file_get_contents("php://input"), when data length is lower than 8 KBs the php code is executed, otherwise it can't be executed. In the other hand php didn't receive the request.
the code C#:
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
// postData is Base64_encoded
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseData = reader.ReadToEnd();
responseData = SecurityUtils.DecryptUrlData(responseData);
reader.Close();
dataStream.Close();
response.Close();
return responseData;
Could any one help?
The below is incorrect (mea culpa). You cannot use enctype=multipart/form-data with php://input. See here
Perhaps you can post your PHP code into your question as well?
Make sure that when you POST from the c# app to your PHP app that you set the enctype to multipart/form-data.
Explanaition
Are you using application/x-www-form-urlencoded or multipart/form-data? There is a good explanation of the differenes here: application/x-www-form-urlencoded or multipart/form-data?
According to the link above, posting data in the application/x-form-urlencoded format will put the body into the URL. Many servers and languages (PHP, Apache) will cut off or throw errors when the URL is greater than 8K. See SO question: What is the maximum length for a URL?
Change the content type for the request
request.ContentType = "text/plain";
Check out php.iniĀ“s post_max_size on the server side
Excuse any ignorance on my part with this methodology as it is somewhat new to me. I've been reading up on it as much as I can, but haven't been able to solve this yet.
I'm trying to accomplish a SSO with a vendor through an http post. Simple enough. I've done this in the past, but it usually returns a url that I can then redirect the user to. Unfortunately, with this vendor they are returning the entire page, html and all. Is this typical? If so, is my only solution to post this to a new window?
For reference, here's my code so far:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] postBytes = Encoding.UTF8.GetBytes(postString);
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseReader = new StreamReader(responseStream);
var responseString = responseReader.ReadToEnd();
responseReader.Close();
responseStream.Close();
response.Close();
Does everything look normal and ok so far?
It is normal for a POST request to return a new web page. I would think the redirect would be the abnormal case.
You're pretty vague about your app, so I'm not sure how you'll want to get the returned html shown to the user.
You might want to check out the WebClient class which could simplify your code considerably.
using (var client = new WebClient())
{
var resultBytes = client.UploadData(new Uri("http://example.com"), "POST", data);
}
Im stuck on this httpWebRequest problem. I need to send XML to a website. But I keep getting negative responses on my request. I saw some code examples where the ContentLength was set... And that might be the issue but I don't know....
The XML written in writePaymentRequest(...) is exactly as the website needs it to be, because they got my xml markup and they succeeded, in another programming language though. The result only contains their error instead of the information I'm supposed to be receiving.
I can't set the contentlength because I don't know the length when I create the writer with the requeststream in it.
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://some.website.com");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
using (writer = new XmlTextWriter(httpWebRequest.GetRequestStream(), System.Text.Encoding.UTF8))
{
writePaymentRequest(writer, registrant, amount, signature, ipaddress);
}
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
String stringResult = streamReader.ReadToEnd();
streamReader.Close();
You would know the length if you wrote the XmlTextWriter to something like a MemoryStream first. From there, you could get the bytes, set the httpWebRequest.ContentLength to the length of the byte array, and then write the byte array to your request
edit
The middle of your code would look something like this (I think):
MemoryStream ms = new MemoryStream();
using (writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8))
{
writePaymentRequest(writer, registrant, amount, signature, ipaddress);
}
byte[] bytes = ms.ToArray();
ms.Close();
httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
httpWebRequest.ContentLength = bytes.Length;
edit #2
Instead of XmlTextWriter(ms, System.Text.Encoding.UTF8), try XmlTextWriter(ms, new UTF8Encoding(false)) to see if that fixes the encoding issue