我试图获取并设置 Json,但在“endgetresponse”上有一个例外:
public void GetSetJsonString (string message)
{
this.message = message;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myurl);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = "POST";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(myurl, myfirstcookie);
request.CookieContainer.Add(myurl, mysecondcookie);
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(message);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string answer = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
}
}
就行了 HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
我得到了这个例外:
{System.Net.WebException:远程服务器返回错误:NotFound。---> System.Net.WebException:远程服务器返回错误:NotFound。在 System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) 在 System.Net.Browser.ClientHttpWebRequest.<>c_ DisplayClasse.b _d(Object sendState) 在 System.Net.Browser.AsyncHelper.<>c_ DisplayClass1.b _0 (Object sendState) --- 内部异常堆栈跟踪结束 --- 在 System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) 在 System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 在项目。 System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClass1d 处的 GetSetJson.GetResponseCallback(IAsyncResult asynchronousResult) 。_1b(对象状态2)}
奇怪的是,当我作为错误发送的 Json 消息时,我没有出现异常,并且我收到了来自服务器的错误消息。
您知道我为什么会出现此异常以及如何解决此问题吗?
非常坦克你!