我只想在http://www.test.com/test.asp?test1=3上执行http发布。这是我一直在尝试使用的代码:
private void pif_test_conn()
{
Uri url = new Uri("http://www.test.com/test.asp?test1=3", UriKind.Absolute);
if (httpResult == true)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
return ;
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
MessageBox.Show("Using HttpWebRequest: " + resultString, "Found", MessageBoxButton.OK);
}
}
当我执行此代码时,我的程序会触发Application_UnhandledException事件。不确定我做错了什么。
答案 0 :(得分:6)
您是否想要发布给其他主持人?这种行为可能会导致XSS安全问题,因此无法使用。
string responseValue = "";
AutoResetEvent syncRequest = new AutoResetEvent(false);
Uri address = new Uri(HtmlPage.Document.DocumentUri, "/sample.aspx");
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
{
// Send packet data
using (Stream post = request.EndGetRequestStream(getRequestResult))
{
post.Write(buffer, 0, buffer.Length);
post.Close();
}
// wait for server response
request.BeginGetResponse(getResponseResult =>
{
WebResponse response = request.EndGetResponse(getResponseResult);
responseValue=new StreamReader(response.GetResponseStream()).ReadToEnd();
syncRequest.Set();
}, null);
}, null);
syncRequest.WaitOne();
MessageBox.Show(
"Using WebRequest: " + responseValue,
"Found", MessageBoxButton.OK);
HTH
答案 1 :(得分:4)
您只能将HTTP请求发送到您的应用来自的域。
此限制可防止XSS攻击。
答案 2 :(得分:1)
如果您离开SyncRequest.WaitOne()
来电,则通话死锁,至少在Silverlight 4.0中。
答案 3 :(得分:0)
要发送HTTP POST,您需要通过调用BeginGetRequestStream
方法将POST数据写入请求。
这可能是你获得例外的原因;请告诉我们您正在寻找更具体的答案的例外情况。