I have the below code in a webservice to read the post data. The issue here is whenever the request contains special character, lets say "amé", the character is replaced as am� while converted to string.
byte[] postData= HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength);
string strReq = Encoding.UTF8.GetString(postData);
And I call the WebService with the below code:
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "text/xml; charset=utf-8";
webClient.Headers[HttpRequestHeader.Authorization] = credentials;
string output = webClient.UploadString(url, "POST", input);
You'll need to specify in your web service that the post data is UTF-8 encoded, otherwise you won't be able to decode it as UTF-8. Adding charset=utf-8 to the end of your content-type header should do the trick.
e.g.
'content-type': 'text/xml; charset=utf-8'
Note that specifications for JSON and form encoded POST data require UTF-8.
Related
I have one URL with some special characters like | and &.
URL is returning JSON data.
When I am trying this URL in browser it will run and return json data but when I am trying using WebClient.DownloadString(), it will not work.
Example :
Using Browser :
http://websvr.test.com/abc.aspx?Action=B&PacketList=116307638|1355.00
Output :
[{"Column1":106,"Column2":"Buying Successfully."}]
Using WebClient.DownloadString():
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://websvr.test.com/abc.aspx?Action=B&PacketList=116307638|1355.00");
}
Output :
[{"Column1":-107,"Column2":"Invalid Parametrer Required-(RefNo|JBPrice)!"}]
You should encode PacketList parameter in your URL, because it includes pipe character, which must be encoded to %7c. Browsers automatically encode necessary characters in URL, but you should encode it in code manually.
var json = wc.DownloadString("http://websvr.test.com/abc.aspx?Action=B&PacketList=" +
System.Web.HttpUtility.UrlEncode("116307638|1355.00");
Try to set webclient's encoding before call DownloadString() and encode url using UrlEncode Method :
WebClient.Encoding = Encoding.UTF8;
var url = WebUtility.UrlEncode("http://websvr.test.com/abc.aspx?Action=B&PacketList=116307638|1355.00");
var json = wc.DownloadString(url);
I am trying to send a POST request in C# with a parameter encoded to ISO-8859. I am using this code:
using (var wb = new WebClient())
{
var encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
var encodedText = System.Web.HttpUtility.UrlEncode("åæ ÆÆ øØ ø", encoding);
wb.Encoding = encoding;
wb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var data = new NameValueCollection();
data["TXT"] = encodedText;
var response = wb.UploadValues(_url, "POST", data);
}
I have figured out that the correctly encoded string for "åæ ÆÆ øØ ø" is %E5%E6+%C6%C6++%F8%D8+%F8, and I can see when debugging that encodedText actually is this string. However when inspecting the raw request in fiddler, I can see that the string looks like this: TXT=%25e5%25e6%2B%25c6%25c6%2B%25f8%25d8%2B%25f8. I am guessing some kind of extra encoding is being done to the string after or during the call to UploadValues().
Thank you so much in advance.
I checked Google for this. According to another question here on SO at UTF32 for WebClient.UploadValues? (second answer), Webclient.UploadValues() indeed does encoding itself. However, it does ASCII encoding. Youll have to use another method to upload this, like HttpWebRequest.
I have a controller that is building using a StringBuilder called param to create a string to post to a REST service. The string that is passed is a query string that will get parsed. I'm encoding the values for each pair so that ampersands, doesn't inadvertantly create a new key.
An encoded param string might look like
clientType=MyClient&form_id=webform_client_form_38&referrer=http://mywebsite&company=My+%26+Company
Here is the code I'm using to send to the REST service
byte[] formData = UTF8Encoding.Default.GetBytes(param.ToString());
req.ContentLength = formData.Length;
//Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
When I debug the REST service the string is always encoded back, adding the ampersand back between My and Company.
Is there another built in method that will convert the string to a byte without encoding the text?
You can't use a HTML Decode function? that will transform back the string to the correct string that you sent.
HttpUtility.HtmlDecode
How do i get the data inside an HTTP POST request , that is received in my WCF Service?
i send the data from another service using HTTP POST:
string ReportText = "Hello world";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(ReportText);
// Prepare web request...
String serverURL = ConfigurationManager.AppSettings["REPORT"];
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serverURL);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
but when i receive the POST request in the WCF i can't find a way to extract it using WebOperationContext.Current.IncomingRequest,
how do i extract the data from the HTTP POST request ?
My guess is that you are using a WCF Rest service and you can pull the GET parameters but you are unable to read RAW post data?
If this is the case then add a Stream parameter to the end of the parameter list in the Contract declaration. If there is a single stream at the end of the function, the framework treats it as a raw data stream.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "DoSomething?siteId={siteId}&configTarget={configTarget}",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool DoSomething(string itemid, Stream body);
public bool DoSomething(int siteId, string configTarget, Stream postData)
{
string data = new StreamReader(postData).ReadToEnd();
return data.Length > 0;
}
See this link for more details:
http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx
Hello world isn't exactly application/x-www-form-urlencoded. You need to encode the post message body accordingly someproperty=Hello%20world as well as use WCF HTTP bindings.
This isn't a WCF question, as you're not using WCF. What you're really doing is submitting a form using HTTP Post, and you need to make a web page to receive and handle that. You can do that with the Request.Form collection.
Here's a simple example: http://bytes.com/topic/asp-net/answers/655226-how-use-request-form
We have webpage in our project where website post the XML data to.
string data = string.Concat("XMLParameter=", SampleXML, "&", "AccessCode=", "XYZ");
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream()); string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
When we pass following XML with post,
<notification timestamp="2009-09-11T11:51:07+02:00">
<reservation creation_date="2010-09-10T12:03:13">
</reservation>
</notification>
On the receiving end in our web page, timestamp we receive do not contain +. Instead of +, it gives us Space charactor. So, while deserializing it, we got error.
We get the data in page using Request.Form["XMLParameter"]
Any solution ???
You have a funny service where the XML data is posted as if it were coming from an HTML form with a text field containing the XML data.
As a consequence, the web server expects your data to be URL encoded. You even tell in the content type that it's encoded. But it isn't. You don't encode it anywhere in your code.
So if you want to stick with your funny service, then you need to run your XML data through HttpUtility.UrlEncode first.