Android登录应用程序到网站

时间:2012-05-01 16:17:47

标签: android cookies login parameters http-post

所以iam试图从这个服务器成功登录:www.liuserver.com和我使用两个类LoginLayout.java和CustomHttpclient.java,现在我已经使用Httpwatch监控浏览器与服务器的通信以便跟踪服务器产生的回复类型和帖子(产生包含用户提供的用户名和密码的url,除了自动生成的x和y整数,在本例中为31和1,其他时间为hey只是零)网页看起来像这样:

POST /login.php HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap,     application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Referer: https://www.liuserver.com/login.php
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR     3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: www.liuserver.com
Content-Length: 38
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: PHPSESSID=e3q4d78jkci3shhn8fq1tlf7i5

USER=20730312&PASS=Password44&x=32&y=1

现在我已成功生成带参数的url,我将它们发布到服务器但当然它给了我否定回复,现在我已被告知,这在httpwatch插件的cookies选项卡中显而易见,我需要将phpsessionid作为cookie发送,我的问题是如何能够做到这一点以及我应该在哪个类中放置用于发送带参数的cookie的代码,以及如何跟踪服务器的回复类型成功验证用户名和密码后。 回复流看起来像:

HTTP/1.1 302 Found
Server: nginx/1.0.14
Date: Tue, 01 May 2012 15:57:06 GMT
Content-Type: text/html
Connection: keep-alive
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: student/
X-Powered-By: PleskLin
Content-Length: 0

登录页面的完整网址:https://www.liuserver.com/login.php

更新:

好的,我已成功从服务器获取phpsessionid cookie,我可以查看它的值,现在我必须使用

将我的登录参数提交给erver
response = CustomHttpClient.executeHttpPost("https://www.liuserver.com/login.php", postParameters);

但是我应该在这个方法中将包含phpsession id的cookie放在哪里executehttpPost我可以更改方法的参数并将cookie传递给那里吗?

2 个答案:

答案 0 :(得分:1)

要保存Cookie,您需要以下内容:

CookieStore cookieStore = new BasicCookieStore();
DefaultHttpClient httpclient = new DefaultHttpClient();

HttpContext ctx = new BasicHttpContext();
ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet get = new HttpGet("your URL here");

HttpResponse response = httpclient.execute(get,ctx);

如果您想在请求之间保留Cookie,则必须为每个请求重复使用cookieStorectx

另外,您可以阅读cookieStore以查看其中的内容:

List<Cookie> cookies = cookieStore.getCookies();
if( !cookies.isEmpty() ){
    for (Cookie cookie : cookies){
        String cookieString = cookie.getName() + " : " + cookie.getValue();
        Log.info(TAG, cookieString);
    }
}

答案 1 :(得分:0)

如果您想直接使用标题,那么您的Cookie会作为HTTP回复标题的一部分传递(就像在POST中一样)。

但正如另一张海报所说,如何处理cookie(正确)是他发布的示例,它最终将帮助您正确使用API​​,即使它可能是一个痛苦,了解它是如何工作的第一次: - )