標籤:
本人是個大二學生,由於學校的教務線上一直沒出windows phone的教務線上,而且本身也對wp開發感興趣,所以就嘗試著開發一下
由於沒有系統的學習,只能在摸索中前進,這背後的原理很簡單,可不容易實現,網上也沒合適的教程,下面是本人嘗試著寫登入頁面的代碼,
不過還是有些文法上的問題,希望能幫看看
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections.Specialized;
using System.Text;
using System.Xml.Linq;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async void button_Click(object sender, RoutedEventArgs e)
{
//這句postdata的拼字可能有錯誤,考慮用索引值對的方式
string loginstr = "j_username=" + textBox1.Text + "&j_password=" + passwordBox.ToString();
CookieContainer cookie = await GetCookie(loginstr,"http://60.18.131.131:11080/newacademic/common/security/login.jsp");
string content = await GetContent(cookie, "http://60.18.131.131:11080/newacademic/frameset.jsp");
Frame.Navigate(typeof(BlankPage1), content);
textBox2.Text = content;
}
public async Task<CookieContainer> GetCookie (string postString,string postUrl)
{
CookieContainer cookie = new CookieContainer();
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
//下面這個要求標頭的資訊不知如何改進啊,反正有什麼我就把它添上了
httpRequest.CookieContainer = cookie;//設定cookie
httpRequest.Method = "POST";//POST提交
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString);
Stream stream = await httpRequest.GetRequestStreamAsync();
stream.Write(bytes, 0, bytes.Length);//以上是post資料的寫入,不知還有什麼疏漏之處
HttpWebResponse httpResponse =(HttpWebResponse)await httpRequest.GetResponseAsync();
return cookie;
}
public async Task<string> GetContent(CookieContainer cookie,string url)
{
string content;
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.CookieContainer = cookie;
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Method = "GET";
HttpWebResponse httpResponse = (HttpWebResponse)await httpRequest.GetResponseAsync();
using(Stream responseStream = httpResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream,System.Text.Encoding.UTF8))
{
content = sr.ReadToEnd();
}
}
return content;
}
}
}
邏輯上大致是先類比登陸,然後拿到cookie,再帶著這個cookie訪問登陸上的網頁,(然後通過解析html擷取自己想要的內容,這部分還沒做)
不過並不能取到所返回的content,希望有經驗的園友指導一下
Windows phone8.1教務線上用戶端