Help with C# HttpWebRequest URI losing its encoding

守給你的承諾、 提交于 2019-12-18 13:15:32

问题


Having a problem with HttpWebRequest decoding my encoded URL.

var requestUrl = "https://www.google.com/webmasters/tools/feeds/http%3A%2F%2Fwww%2example%2Ecom%2F/crawlissues/";   
var request = (HttpWebRequest)WebRequest.Create(requestUrl);

When looking at end request URL is becomes:

https://www.google.com/webmasters/tools/feeds/http://www.example.com//crawlissues/

Which of course returns a 400 Bad request. I am guessing it is something todo with the URI class rather than HttpWebRequest. How do I stop this from happening?


回答1:


This is an annoying "security feature" of the Uri class. If you're using 4.0 or later, you can turn it off in your configuration file; otherwise, you'll have to resort to reflection.




回答2:


I don't think you can request that url.

It won't decode %2F in a query parameter. So, it would work if the encoded data was in a query parameter:

requestUrl = "https://google.com/tools?feeds=http%3A%2F%2Fwww%2example%2Ecom%2F/crawlissues/";   
var request = (HttpWebRequest)WebRequest.Create(requestUrl);



回答3:


There is a much simpler way to this

var request=(HttpWebRequest)WebRequest.Create(Uri.EscapeUriString(requestUrl));
request.Headers.Add("Content-Transfer-Encoding","binary");

worked like a charm for me




回答4:


Not sure but may be HttpServerUtility.UrlEncode method will help.

Upd. Alternatively you may use WebClient class.




回答5:


Try to change the Request method from POST to GET



来源:https://stackoverflow.com/questions/2287639/help-with-c-sharp-httpwebrequest-uri-losing-its-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!