send "#" and "&" character through XML request - c#

I need to send special character through XML request. to complete this action, I convert the string to UTF-8, as XML always use UTF-8 data encoding.[using below code]
byte[] myBytes = Encoding.Default.GetBytes(MyMessage);
MyMessage = Encoding.UTF8.GetString(myBytes);
I am able to send all the special characters like "!#$%^*()<>?" except "#" and "&". But those two character in very vital for me to send. how can I send those two character through XML.
I also try to replace and send using
MyMessage= MyMessage.Replace("&", "&");
MyMessage= MyMessage.Replace("#", "#");
but it also doesn't work.
I have to create a request and send to a URL: sample requesting format is below:
http://1.2.3.4/Default.aspx?MSG_ID=20140107032647101768&BODY=test#&Time=20140107032647102769

Replace & by %26 and # by %23.
This is not XML specific, it's a URL issue. To catch all issuey, try HttpUtility.UrlEncode

Related

Sending query parameters using C#

I want to send a string to a web API using GET. My string contains a few characters that are not accepted in URL or need to be escaped. How can I scape them and send them to the server?
If it helps, my server is written in PHP so any encoding needs to be reversed in PHP.
If your data has HTTP Wildcards in it try to serialize or encode it that outputs a string doesn't contain any HTTP Wildcards.You can pass data with uriencode or some other encoding algorithm like for example (base64) :
string byteArray = System.Encoding.UTF8.GetBytes(yourData);
string encoded = Convert.ToBase64String(byteArray);
string exampleUri="a.com/b.php?data="+encoded;
Decode it in PHP like this :
$data = base64_decode($_GET["data"]);
As i said you can also use uriencoding with :
HttpUtility.UrlEncode / UrlDecode (You need System.Web assembly in your project)

Encode header value using WebClient.Headers.Add()

I am using HTTP headers to send a string which contains Unicode characters (such as ñ) to a custom http server.
When I add the string as a header:
webClient.Headers.Add("Custom-Data", "señor");
It is interpreted by the server as:
se�or
Obviously I need to encode the value differently, but I am unsure what encoding to use.
How should I encode this HTTP header to preserve extended/special characters?
porneL's answer to a related question is confusing.
Unanswered, related: C# WebClient non-english request header value encoding
As #Jordan suggested, representing the string as base64 (with UTF8 encoding) worked well:
On the client side:
webClient.Headers.Add("Custom-Data",
Convert.ToBase64String(Encoding.UTF8.GetBytes("señor")));
And on the server:
string customData = Encoding.UTF8.GetString(Convert.FromBase64String(customHeader.Value));

C#: Sending HTTP GET request without UTF-8 encoding

I need to send HTTP GET request from C# to CLASSIC ASP service.
The service is built in a way that it decodes the data from the QueryString using Windows-1255 encoding, rather than the standard UTF-8.
It seems that HttpWebRequest class always encodes GET data with UTF-8 and it doesn't work for me. Is there any way to send HTTP GET request from C#, while GET data is encoded with different than UTF-8 encoding?
Thanks.
You need to set a header on your get request:
Content-Type:text/xml; Charset=windows-1255
HttpRequest r = new HttpRequest(.....);
r.Headers.Add("Content-Type", "text/xml; Charset=windows-1255");
Maybe this post will be of some use too:
Read non-english characters from http get request
Ok, I finally got the answer.
First of all, specifying ContentType in the header doesn't work.
If destination URL is containing none-English letters, the HttpWebRequest will always use UTF-8 + URLEncode to build the final URI the request is sent to.
To use encoding different from UTF-8 I needed to encode URL values by myself (instead of providing necessary encoding to HttpWebRequest as I expected).
Following function that builds HTTP GET URL, while values are encoded with any requested encoding (and not with the default UTF-8):
string BuildData(NameValueCollection getData, Encoding enc)
{
StringBuilder urldata = new StringBuilder();
for (int i = 0; i < getData.Count; i++)
{
if (i > 0) urldata.Append("&");
urldata.Append(getData.Keys[i] + "=" + HttpUtility.UrlEncode(enc.GetBytes(getData[i])));
}
return urldata.ToString();
}
The HttpWebRequest can be used with something like
"http://get-destination.com/submit?" + BuildData(keysAndValues, Encoding.GetEncoding(1255));
In this case HttpWebRequest gets already encoded URL which doesn't contain none-English letters and it keeps it as is.

USPS Address Validation Fail

When validating an address, I get this error:
ex = {"Error Loading XML: The following tags were not closed: AddressValidateRequest, Address, Address1.\r\n"}
or I get another error saying the address cannot be found. Is there a better way to validate this address?
Here is my URL:
http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=<AddressValidateRequest USERID="402JMAWE3481"><Address ID="1"><Address1>123 Main St</Address1><Address2></Address2><City>Watertown</City><State>MA</State><Zip5>02472</Zip5><Zip4></Zip4></Address></AddressValidateRequest>
According what I see on the error description, the problem could be that you need to remove \r\n from the xml before adding it to the url. Don't forget also to url encode it.
You actually need to HtmlEncode it and then UrlEncode it.
This is becasue you're actually sending XML (which requires & instead of &) but its a URL so it needs encoding to make each & into %26
Here's a complete working URL - you just need to put in your USERID.
http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=<AddressValidateRequest USERID="123USERID567"><Address ID="1"><Address1></Address1><Address2>10051+Orr+%26amp%3b+Day+Rd</Address2><City>santa+fe+springs</City><State>ca</State><Zip5>90670</Zip5><Zip4></Zip4></Address></AddressValidateRequest>
You'll see it contains this funky looking string:
10051+Orr+%26amp%3b+Day+Rd
Which I got by doing this :
HttpUtility.UrlEncode(HttpUtility.HtmlEncode("10061 Orr & Day Rd"))
[This specific error I got back when I didn't encode properly was Error Loading XML: Whitespace is not allowed at this location]

Encoding my string to send an http request via C#

I am trying to send a simple HTTP request like this:
var client = new WebClient();
string myString="this is the string i want to send";
message = client.DownloadString("http://www.viralheat.com/api/sentiment/review.xml?text=" + myString + "&api_key="+currentKey);
but some of the strings I send includes # or & or such characters, so I want to encode the string first before sending it, because it throws an error if it includes these special characters without being encoded.
Call Uri.EscapeDataString.
Unlike HttpUtility, this works on the client profile too.
Use HttpUtility.UrlEncode

Categories

Resources