1
閱讀一些資源用於製作HttpClient的建設,通過網站(POST方法)上可用的形式進行登錄後,我寫了這個方法:的Android HttpClient的POST表單登錄
public void connect(View v) {
final String TAG = ">>>>>>>>>>>> Activity Log: ";
request = new HttpGet("http://www.mysite.com/login");
try {
response = client.execute(request);
} catch (ClientProtocolException e3) {
e3.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
entity = response.getEntity();
Log.d(TAG, "Login form get: " + response.getStatusLine());
if(entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Initial set of cookies:");
cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty())
{
Log.d(TAG, "None");
}
else
{
for(int i = 0; i<cookies.size(); i++)
{
Log.d(TAG, "- " + cookies.get(i));
}
}
String action = "/login.php";
String yourServer = "http://www.mysite.com";
post = new HttpPost(yourServer + action);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "myuser"));
params.add(new BasicNameValuePair("password", "mypass"));
try {
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
try {
response = client.execute(post);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
entity = response.getEntity();
Log.d(TAG, "Login form get: " + response.getStatusLine());
if(entity != null){
try {
entity.consumeContent();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Post logon cookies:");
cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty())
{
Log.d(TAG, "None");
}
else
{
for (int i = 0; i < cookies.size(); i++) {
Log.d(TAG, "- " + cookies.get(i));
}
}
}
但無論我把作爲用戶名/密碼我得到狀態:「OK 200」。而作爲餅乾我得到這樣的:
[版本:0] [名稱:PHPSESSID] [值: 9ismhf3p5c282p1east0drme02] [域名: .mysite.com] [路徑:/] [屆滿: 空]
當我嘗試訪問某些不可用於未登錄用戶的URL時,我得到登錄表單頁面。我如何知道我已成功登錄並訪問不可用的URL?
您確定將您從登錄表單中獲得的cookie與您的請求一起發送到受限制的頁面嗎? – WesleyE 2011-01-23 17:12:15