我正在创建一个应该执行以下操作的 Android 应用程序;
- 使用 https (SSL!) 页面上的表单登录并接收 cookie
- 发出 httpGET 操作以获取 html
- 解析该 html 并将其显示在视图、列表或其他内容中。
很长一段时间以来,我一直在玩弄 Jsoup、httpUnit 和 HTMLUnit,但我遇到了几个问题;
A. 登录很好,工作..(我得到了网站的欢迎页面)但是,当我发出 GET 语句(并包含 cookie)时,我被重定向到登录表单。所以响应 html 不是我所期望的。(可能与keepalivestrategy有关?)
B. InputBuffers 太小,无法接收整个 HTML 页面并设置它们进行解析。
注意:我无法控制网络服务器
我对此完全陌生,因此教程或代码片段会有所帮助。
例如,这是我用来登录网站的:
public int checkLogin() throws Exception {
ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("userid", getUsername()));
data.add(new BasicNameValuePair("password", getPassword()));
data.add(new BasicNameValuePair("submit_login", "Logmein"));
Log.d(TAG, "Cookie name : " + getCookieName());
Log.d(TAG, "Cookie cont : " + getCookie());
HttpPost request = new HttpPost(BASE_URL);
request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.getParams().setParameter("http.protocol.handle-redirects",false);
request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
HttpResponse response;
httpsclient.getCookieStore().clear();
List<Cookie> cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies pre-login : " + cookies.size());
response = httpsclient.execute(request);
cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies post-login : " + cookies.size());
String html = "";
// Problem : buffer is too small!
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
Document doc = Jsoup.parse(html);
Log.v(TAG, "Ik heb nu dit : " + doc.toString());
if (cookies.size() > 0){
storeCookie(cookies.get(0).getName(), cookies.get(0).getValue());
return MensaMobileActivity.REQUEST_SUCCESS;
} else {
return MensaMobileActivity.REQUEST_ERROR;
}
}