开发者

c# WebClient problem using a URL with URL-encoded cyrillic chars

I'm tryinig to load a file from a web server with a request URL that contains a parameter with cyrillic chars. But I'm not getting this to work in c#, even if I URL-Encode the param.

When I open the page in IE with

http://translate.google.com/translate_tts?tl=ru&q=ЗДРАВСТВУЙТЕ

the server does not respond.

Using the URL-encoded version

http://translate.google.com/translate_tts?tl=ru&q=%d0%97%d0%开发者_Python百科94%d0%a0%d0%90%d0%92%d0%a1%d0%a2%d0%92%d0%a3%d0%99%d0%a2%d0%95

the server responds as expected.

Now my problem:

I want to download the MP3 from C# ...

var url = string.Format("http://translate.google.com/translate_tts?tl=ru&q={0}", 
          Server.UrlEncode("ЗДРАВСТВУЙТЕ"));
System.Net.WebClient client = new WebClient(); 
var res = client.DownloadData(url);

And this does NOT work with cyrillic chars. I always get a zero-byte answer, like the first, non-encoded request. When I send "normal" chars, the code above works fine.

So ... I'm doing something wrong. Any hints? Tipps? Solutions?

Thanks

Michael


You have to set the user-agent for the WebClient - this works:

string url = "http://translate.google.com/translate_tts?tl=ru&q=ЗДРАВСТВУЙТЕ";
WebClient client = new WebClient();
client.Headers.Add("user-agent", 
                   "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var res = client.DownloadData(url);

From the msdn documentation:

A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing.


Try to add

client.Encoding = System.Text.Encoding.UTF8;

I don't use user-agent header but for me it works:

WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
string response = client.DownloadString(_url);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜