Skatrix
Skatrix

Reputation: 139

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.

Upvotes: 1

Views: 3626

Answers (2)

Skatrix
Skatrix

Reputation: 139

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.

Upvotes: 1

MiiisterJim
MiiisterJim

Reputation: 429

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

Upvotes: 2

Related Questions