private void SendPost() { var url = http://ip:port/test.jsp; // Create the web request object HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; // Start the request webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest); } private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState; // End the stream request operation Stream postStream = webRequest.EndGetRequestStream(asynchronousResult); // Create the post data // Demo POST data string postData = "SubmitIMLogin=1&phone=11111111"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); // Start the web request webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest); } private void GetResponseCallback(IAsyncResult asynchronousResult) { try { HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response; // End the get response operation response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult); Stream streamResponse = response.GetResponseStream(); StreamReader streamReader = new StreamReader(streamResponse); var Response = streamReader.ReadToEnd(); streamResponse.Close(); streamReader.Close(); response.Close(); Dispatcher.BeginInvoke(() => //传给主线程结果 { MessageBox.Show(Response); }); } catch (WebException e) { Dispatcher.BeginInvoke(() => //传给主线程结果 { MessageBox.Show(e.ToString()); }); } }
帮我解决这个异常。
或者你能否给我一个简单的例子,一个地址一个参数。用Http Post 的方式获取数据呢
Url:http://ip:port/11111.asp
postData:SubmitIMLogin=1&phone=111111
你是想Post data,还是想从模仿Web Server那样?
如果是Post data
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
var stream=webRequest.GetRequestStream(); //往Stream 写 postData。
@哲凯: 手上暂时没有IDE,将就一下
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
var stream=webRequest.GetRequestStream();
using(var writer=new StreamWriter(stream))
{
writer.Write(postData);
writer.Flush();
}
responseStream = webRequest.GetResponse().GetResponseStream();
using(var reader=new StreamReader(reponseStream))
{
// do sometihing.
}
@沉默的糕点: 返回值在什么地方获取?
@哲凯:
ResponseStream 就是你要的返回值,按照字符方式处理就可以了,也就是说,你返回的是Json,那么就按Json处理,如果是Html,那么久里面就是Html。
@沉默的糕点: 恕在下,不知。
我先试试,总之还是谢谢你的帮助!
我要的是在widowc Phone里面进行Post不是asp.net啊。Phone里面好多东西都没有!
牛,搞WP的!应该思路差不多,只是WP把很多东西都省略了,毕竟运行环境不同。
不过呢,你可以把.NET里的实现过程反射出来分析,然后想办法在WP中自己写一个类库来实现,就用Waters提供的连接http://www.cnblogs.com/ThomasNet/archive/2007/09/03/879331.html,我一般都是用这样的方法解决,呵呵,有点暴力有点黄。
同求解 我也是这样写 但是到了Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
就报错 各种不懂啊