首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用WebRequest的System.Net.WebException

使用WebRequest的System.Net.WebException
EN

Stack Overflow用户
提问于 2014-10-27 13:50:57
回答 1查看 896关注 0票数 0

我正在努力尝试使用WebRequest类来获取downloading.It工作的句柄网址,除了当我输入诸如https://soundcloud.com/top-bollywood-songs/atif-aslam-mashup-full-song-dj (最后一段扩展名)之类的链接时,它抛出System.Net.WebException并返回“The remote server return an error:(400) Bad Request”。

代码语言:javascript
复制
  WebResponse response = (WebResponse)request.GetResponse();

请提建议!

EN

回答 1

Stack Overflow用户

发布于 2014-10-27 13:57:43

您可以添加用户代理。以下是一个工作示例:

代码语言:javascript
复制
protected string getHTML(string url)
{
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            // ******  Add the this line! ****//
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            string html = readStream.ReadToEnd();
            response.Close();
            readStream.Close();
            return html;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26581832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档