我正在使用 WebClient
类在 C# 中调用一个 URL。以下是代码:
public string SendWebRequest(string requestUrl)
{
using (var client = new WebClient())
{
string responseText = client.DownloadString(requestUrl);
return responseText;
}
}
这段代码出现了以下异常细节:-
System.Net.WebException: The remote server returned an error: (1201).
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
Exception Status: ProtocolError
URL已经成功地到达服务器。服务器上预期的操作(更新数据库)正常进行。服务器正确地发送响应。但是,WebClient
未能处理响应。
我也尝试使用HttpWebRequest
类,但没有成功。
最初,在请求时出现了类似的问题。当我按照以下方式修改了我的app.config
后,问题得到了解决:
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
我不能在这个论坛上发布URL,而且在网络外也无法访问。
如果我将相同的URL复制到浏览器地址栏中,它可以正常工作并返回预期的响应。
那么Windows应用程序可能有什么问题呢?
编辑1
我实现了答案中的建议。我还实现了接受答案中此问题的建议。现在,我的函数如下所示:-
public string SendWebRequest(string requestUrl)
{
using (var client = new WebClient())
{
client.Headers.Add("Accept", "text/plain");
client.Headers.Add("Accept-Language", "en-US");
client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
client.Headers["Content-Type"] = "text/plain;charset=UTF-8";
string responseText = client.DownloadString(requestUrl);
return responseText;
}
}
它仍然没有解决问题。现在响应是空字符串(""),而不是"Success"。这不是服务器的错误,已经确认。
如果我删除app.config
中的配置,它会抛出其他异常。
System.Net.WebException: The server committed a protocol violation. Section=ResponseStatusLine
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
Accept
),以及服务器可能需要的任何其他头部(例如User-Agent
)。 - Matias Cicero