VS10中用C#写的HttpWebRequest请求的url被自动修改编码,无法获取想要的结果

2025-05-19 14:54:30
推荐回答(2个)
回答1:

string url="http://www.scgis.net.cn/imap/imapserver/defaultrest/services/Newscnamesearch/Search?keyname=%u516C%u53F8&DiQuKey=&QuXianKey=&isOnlyName=false&SearchEnvelope=&typeCode=&StartIndex=0&StopIndex=100&token=&pretty=true&st=1405823574713";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url ); httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = 20000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string jsonstr = sr.ReadToEnd();

如果按照您的代码这样去请求.他自身是会被改动成这个样子的..
原因呢?
是因为您本地的环境自身就不太符合您编码的格式.

最根本的解决办法.C#拥有URL编码的类库

在Asp.net中可以使用Server.HTMLEncode和Server.URLEncode 将文本或URL的特殊字符编码,
但在控制台或Winform程序中没有办法使用到这些方法,

解决办法:

右击项目==》添加引用==》.NET==》System.Web==》确定

System.Web.HttpUtility.HtmlEncode(str);
System.Web.HttpUtility.HtmlDecode(str);

System.Web.HttpUtility.UrlEncode(str);
System.Web.HttpUtility.UrlDecode(str);

编码后得到的字串和用Server.URLEncode编码得到的不一样

编码时可以指定编码的,如
System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.Unicode);
System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.UTF8);
System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.GetEncoding( "GB2312 "));


解码也可以指定编码的
System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.Unicode);
System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.UTF8);
System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.GetEncoding( "GB2312 "));

回答2:

我今天遇到了同样的问题,string url="http://www.scgis.net.cn/i..... 其实只要把 http改成https就搞定了