读书人

WindowsPhone模拟登陆时怎么判断是否已

发布时间: 2012-12-26 14:39:28 作者: rapoo

WindowsPhone模拟登陆时如何判断是否已登陆成功?
登陆时访问的页面是http://api.website.com/login.php。若登陆成功,则该页面会返回{"title":1,"userid":1734,"list":[{"s_id":"3"}],"tokenlist":[{"s_id":"3","token":"173899|6.80b926c2778fc1aea416c90e800b8623.2592000.1348992000-261351411","token_secret":"173899|0.ny8z8q4KgpkzST3J5xw4kA5kRr2R230l.261351411","u_id":"261351411"}],"silencetime":{"start_time":"09:00","end_time":"22:00"},"version":10}
若登录失败,则页面返回{"title":2}
登陆代码如下:


private void LoginButton_Click(object sender, RoutedEventArgs e)
{
try
{
API loginapi = new API();
bool res;
string username = this.LoginName.Text;
string password = this.LoginPassword.Text;
res = loginapi.login(username,password);
if (res) this.NavigationService.Navigate(new Uri("/MainContentPage.xaml", UriKind.Relative));
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
}
}

若希望登陆成功才转到MainContentPage.xaml,否则提示“登录失败,密码错误”,该如何实现?
[最优解释]
可以用一个while循环,里面判断连接状态。

int delay = 5;
while (request.statusCode!= HttpStatusCode.OK)
{
Thread.Sleep(1000);
delay--;
if (delay <= 0)
{
MessageBox.Show("超时!");
return false;
}
}

[其他解释]
我猜这应该是以OAuth作为认证方式的OpenAPI吧。
建议你好好看看OAuth的认证流程,需要几个步骤的。
[其他解释]
用的不是OAuth,是HttpWebRequest等自带类,代码如下:

public string paramData = string.Empty;//请求参数
public string resData = string.Empty;//返回值
public HttpStatusCode statusCode;//状态记录
public Exception errorAsync;//记录异步函数中的错误
public static Encoding dataEncode = Encoding.UTF8;//字符编码方式为UTF8
public void RequestURL(string url)
{
statusCode = HttpStatusCode.Created;
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webReq);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] byteArray = dataEncode.GetBytes(paramData);


postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ee)
{
errorAsync = ee;
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
statusCode = response.StatusCode;
resData = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
}
catch (Exception ee)
{
errorAsync = ee;
}
}


我想通过MessageBox.Show(resData)来查看返回值,可是弹出框里什么也没有,不知道是根本就没有返回值还是我获取返回值的方式不对。

读书人网 >Windows Mobile

热点推荐