当我尝试创建HttpWebRequest
时,它会返回System.Net.ProtocolViolationException
错误。
private void txtGo_Click(object sender, RoutedEventArgs e)
{
WebRequest client =
WebRequest.Create("http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=jdbcn8yuwebwybxjpqzzxyhy");
client.ContentType = "application/json";
client.BeginGetResponse(ReadWebRequestCallBack, client);
}
private void ReadWebRequestCallBack(IAsyncResult callBackResult)
{
var myRequest = (HttpWebRequest) callBackResult.AsyncState;
if(myRequest != null)
{
try
{
var response = (HttpWebResponse)myRequest.EndGetResponse(callBackResult);
txtContent.Text = response.StatusCode.ToString();
}
catch(WebException ex)
{
txtContent.Text = ex.Message;
}
}
}
当我移除这一行代码
client.ContentType = "application/json";
时,会出现一个不同的错误,如下所示。 {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at MyClimate.MainPage.ReadWebRequestCallBack(IAsyncResult callBackResult)}
base: {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult as yncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse. <EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at MyClimate.MainPage.ReadWebRequestCallBack(IAsyncResult callBackResult)}
Response: {System.Net.Browser.ClientHttpWebResponse}
Status: UnknownError
ContentType
后,仅出现了远程服务器返回错误:未找到。
错误。 - user1618825