我从未在httpWebRequest中表现出色。总是首选的WebClient,但......绝望的时间,绝望的措施。
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
//allDone.Set();
}
catch (WebException exception)
{
}
}
我可以看到(当我接下来断点时)responseString是beautiul JSON但我无法将其打印出来(MessageBox等),因为我的应用程序将会中断。
你能告诉我怎么办吗? 干杯
答案 0 :(得分:1)
添加魔法
Dispatcher.BeginInvoke(() => { MessageBox.Show("OK"); });
像魅力一样工作:)
答案 1 :(得分:0)
试试这个
using System.Net;
public void sendRequest()
{
WebRequest webRequest;
webRequest = WebRequest.Create(XXXXXXXXXX);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(newAsyncCallback(GetRequestStreamCallback), webRequest);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "Test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
}
else
{
//Your response will be available in "Response"
}
}
catch (WebException)
{
//error
}
}
此处XXXXXXXX表示您的网址包含发送到服务器的数据。