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));
Related
I'm trying to build a http request using HttpRequestMessage from .net. The problem is that my URL contains %20 in parameters, and I need to send specifically %20 not space caracter. But to use HttpRequestMessage I have to transform my string URL in URI, and then it converts the %20 in space.
I tried a few changes, using encoders before sending to httpRequestMessage. The strange part is that if I encode a "%" for example, it maintain the %25 value, but for spaces does't not.
Example of me testing Uri.ScapeDataString(), look how it keeps the correctly encoding from '['character, but it looses 'space' caracter:
Example with ScapeDataString
For me this is clearly a problem on Uri conversion.
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)
I am using ASP.NET server on .NET 4.5 and client is C# HttpClient on WinRT platform. I want to upload files using the HttpClient and used System.Net.Http.MultipartFormDataContent class to construct a valid http request. Everything worked fine until I had a filename with DBCS characters.
MultiPartFormDataContent class correctly encodes characters in the uploaded filename and sends both filename and filename* keys as per RFC 6266 in the content disposition header.
However, ASP.NET server ignores the filename* and read filename only and hence the file gets saved on the server with weird characters.
Has someone else faced the same problem? How can I get filename* at the server end and ignore filename key from the HttpRequest? [This would be my preferred solution. ]
Alternatively, how can I force MultiPartFormDataContent to send filename key only and force set UTF-8 encoded string?
Add a reference to System.Net.Http and do something like below...
string suggestedFileName;
string dispositionString = response.GetResponseHeader("Content-Disposition");
if (dispositionString.StartsWith("attachment")) {
System.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(dispositionString);
if (!string.IsNullOrEmpty(contentDisposition.FileNameStar))
{
suggestedFileName = contentDisposition.FileNameStar;
}
else
{
suggestedFileName = contentDisposition.FileName.Trim('"');
}
}
ContentDispositionHeaderValue From Microsoft
Late to the party..
With control over both the client and server, my (dirty) workaround was simply to always Base64-encode the filename in HttpClient when creating the content, and decode it again on the server side.
This way you avoid having to deal with the aptly named FileNameStar.
You could also try manually detecting the FileName encoding and decode it on the server.
Related thread: System.Net.Mail and =?utf-8?B?XXXXX.... Headers
TL;DR Düsseldor is encoded to Düsseldor, Düsseldorf isn't encoded (by the default MVC encoding) why?
I'm building an api with soap access. When I get a request I html encode all the data.
Just before I end the current request I copy the Response.Stream and save it for logging.
I noticed that Düsseldorf is encoded by my api to "Düsseldorf". This is expected.
But in my logs it shows Düsseldorf encoded as "Düsseldorf" ( double encoded ) my logs saves after the MVC serializes writes to the response stream.
I think this is because soap encodes values before sending them over the wire.
So my next test was to turn off html encoding in my api.
So this time Düsseldorf was giving to the soap serializer.
But it was encoded as Düsseldorf?
EDIT: When I say I turn on / off the encoding what I mean is each field in the request I use HttpUtility.HtmlEncode("some field"). And save that to the database. Then I return the data with an MVC view like so:
public ActionResult CreateAccessCode ( CreateAccessCodeRequest request )
{
var response = new Response (request);
return new ContentResult (response);
}
My question is when the ContentResult method runs, it seems to do some encoding of its own and I was wondering what that was?
SOAP uses XML - HTML and XML require slightly different encoding, but it may or may not be a problem in your case.
Much more likely your manual construction of XML is not correct. Please do not construct XML with string concatenation - XDocument/XmlDocument are much more suitable for that.
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.