我正在使用C#类调用WebClient中的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: ProtocolErrorURL正确地访问服务器。服务器上预期的操作(更新数据库)正常进行。服务器正确地发送响应。WebClient没有处理响应。
我也尝试过使用HttpWebRequest类,但没有成功。
最初,在提出请求时也存在类似的问题。当我用以下方式修改我的app.config时,它得到了解决:-
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>我不能在这个论坛上张贴网址,无论如何,它是不可访问的外部网络。
如果我在浏览器地址栏中复制相同的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;
}
}它仍然不能解决这个问题。响应现在是空字符串("")而不是“成功”。这不是服务器的错误,这是确认的。
如果删除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)发布于 2016-09-27 12:32:57
您的服务器正在返回HTTP 1201,它不是标准状态码。
当面临一个不成功的状态代码(在您的情况下,是一个无法识别的状态代码)时,WebClient将失败。
如果可以的话,我建议您使用新的HttpClient类:
public async Task<string> SendWebRequest(string requestUrl)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(requestUrl))
return await response.Content.ReadAsStringAsync();
}如果您必须同步执行此操作:
public string SendWebRequest(string requestUrl)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = client.GetAsync(requestUrl).GetAwaiter().GetResult())
return response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}发布于 2016-09-26 14:11:40
尝试更改Try客户端的标题。您的响应似乎与标头类型不兼容。假设您在等待Json,我建议您向客户端client.Headers.Add("Accept", "application/json");添加一个接受头。
https://stackoverflow.com/questions/39704537
复制相似问题