我是Android新手(也是Java),如果我的問題是一個基本命題,非常抱歉! 我必須編寫一個Android應用程序,在後臺登錄aspx網頁,從中獲取一些數據,然後從網頁中註銷。 (和這樣做,所有程序)Android:如何以編程方式登錄到網頁,使用HttpsURLConnection
基本上,該過程喜歡的Gmail電子郵件獲取列表:
1.去 'https://mail.google.com',並在
2跡象。點擊 「聯繫人」(==去 「https://mail.google.com/mail/?shva=1 & ZX = dzi4xmuko5nz#聯繫人」)
3.使用抓取網頁HttpsURLConnection的(或類似的東西),並獲得電子郵件(例如地圖或字符串)對象
4.點擊「退出」鏈接
我希望,這是可以理解的。看着互聯網,我發現只有「取材部分」的解決方案,所以這不是問題。但我對「點擊部分」沒有任何意見。
......
// Get the connection
URL myurl = new URL("https://mail.google.com");
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
// complete the fields
con.setRequestProperty("Email","myacc");
con.setRequestProperty("Passwd","mypass");
/*
* in this part, should make sign in, and go directly to contacts...
* I don't have any idea how to do it...
*/
// for the present, just write out the data
InputStream ins = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.d("Page:"," "+inputLine);
}
in.close();
/*
* And here should be the "Sign out" part
*/
......
任何幫助將是偉大的,謝謝你! (對不起,如果我的英文不太好......)
編輯:問題解決了。謝謝!
.......
String GMAIL_CONTACTS = "https://mail.google.com/mail/?shva=1#contacts";
String GMAIL_LOGIN = "https://mail.google.com";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(GMAIL_LOGIN);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("Email", MY_ACC));
nameValuePairs.add(new BasicNameValuePair("Passwd", MY_PASS));
nameValuePairs.add(new BasicNameValuePair("signIn", "Sign In"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
Log.d(TAG, "response stat code " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() < 400) {
String cookie = response.getFirstHeader("Set-Cookie")
.getValue();
Log.d(TAG, "cookie: " + cookie);
// get the contacts page
HttpGet getContacts = new HttpGet(GMAIL_CONTACTS);
getContacts.setHeader("Cookie", cookie);
response = httpClient.execute(getContacts);
InputStream ins = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
ins));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, " " + inputLine);
}
in.close();
} else {
Log.d(TAG, "Response error: "
+ response.getStatusLine().getStatusCode());
}
.......
謝謝你的回答!遵循這一思路:上面的代碼使用HttpClient,而GMAIL_LOGIN是url,它需要2個參數,email,pass;方法是POST。我認爲,這是你的觀點(1/2/3 /)。我的問題是,在這種情況下我怎麼能得到Cookies,以及如何「瀏覽頁面之間」?你能給我一些關於它的代碼嗎? (我知道我的知識對Java中的Http很差,但是接近完成此任務的時間,並且我被困住了;這就是爲什麼我要求幫助。) – Lama
我編輯我的帖子,其中包含有關第二個請求的信息 – njzk2
感謝代碼!我嘗試過(很多不同類型的),但仍然沒有,我想要的。也許我錯過了一些東西......我編輯第一個評論請提供代碼,如果您有任何問題,請告訴我,錯誤! – Lama