ASP.NET用Post方式向網(wǎng)頁發(fā)送數(shù)據(jù)
ASP.NET項目中用戶提出了新要求,把本來在項目內(nèi)平臺內(nèi)發(fā)送的信息同時發(fā)送到手機上,好在他們已經(jīng)有了短信的發(fā)送平臺,只要調(diào)用其接口發(fā)送就可以了。
短信發(fā)送接口是用JSP實現(xiàn)的一個網(wǎng)頁,調(diào)用方式是以Post方式向該網(wǎng)頁發(fā)送數(shù)據(jù)。
在網(wǎng)絡(luò)上查找資料,幾乎都是同一個結(jié)果:
- System.Net.WebRequest req =
- System.Net.WebRequest.Create(URI);
- req.Proxy = new System.Net.WebProxy(ProxyString, true);
再根據(jù)用戶給定的接口說明和Java例子修改,結(jié)果總是返回的結(jié)果是亂碼,再到網(wǎng)上查,說是編碼方式的問題,那沒有辦法了,只有多方嘗試了。經(jīng)過近一天的不斷試驗,ASP.NET用Post方式向網(wǎng)頁發(fā)送數(shù)據(jù)終于成功了。我的正確的代碼如下:
- protected string SendMsg(string xmlMsg)
- {
- string urlPage =
- "http://www.handtimes.com/interface/forSCMIS.jsp";
- Stream outstream = null;
- Stream instream = null;
- StreamReader sr = null;
- HttpWebResponse response = null;
- HttpWebRequest request = null;
// 要注意的這是這個編碼方式,我嘗試了很長的時間,還有內(nèi)容的Xml內(nèi)容的編碼方式
- Encoding encoding = Encoding.GetEncoding("GBK");
- byte[] data = encoding.GetBytes(xmlMsg);
// 準備請求...
// 設(shè)置參數(shù)
- request = WebRequest.Create(urlPage) as HttpWebRequest;
- request.Method = "POST";
// 這個地方的內(nèi)容類型是接口文檔上要求的,必須是這樣的
- request.ContentType = "text/plain";
- request.ContentLength = data.Length;
- outstream = request.GetRequestStream();
- outstream.Write(data, 0, data.Length);
- outstream.Flush();
- outstream.Close();
//發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
- response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標網(wǎng)頁發(fā)送Post請求
- instream = response.GetResponseStream();
- sr = new StreamReader(instream, encoding);
//返回結(jié)果網(wǎng)頁(html)代碼
- string content = sr.ReadToEnd();
- return content;
- }
要說明的是,發(fā)送時地數(shù)據(jù)的編碼和發(fā)送的內(nèi)容(xml)的編碼都是使用的GBK編碼時成功了,因為用戶給我的帳號不能發(fā)送到我自己的手機上,所以我不敢進行太多的嘗試,成功后就沒有再繼續(xù)嘗試,不知道影響返回的內(nèi)容是亂碼的是哪一個編碼,還是兩個都影響。
- req.ContentType = "
- application/x-www-form-urlencoded";
- req.Method = "POST";
- byte [] bytes = System.Text.
- Encoding.ASCII.GetBytes(Parameters);
- req.ContentLength = bytes.Length;
- System.IO.Stream os = req.GetRequestStream ();
- os.Write (bytes, 0, bytes.Length);
- os.Close ();
- System.Net.WebResponse resp = req.GetResponse();
- if (resp== null) return null;
- System.IO.StreamReader sr = new System.IO.StreamReader
- (resp.GetResponseStream());
- return sr.ReadToEnd().Trim();
這樣就完成了ASP.NET中用Post方式向網(wǎng)頁發(fā)送數(shù)據(jù)。
【編輯推薦】