我正在尝试使用HttpPost登录网站。我的目标是登录并获取网站提供的必要cookie。到目前为止,我已经成功“登录”了,但问题仍然存在于重定向。登录后,我收到来自服务器的成功消息,但实际上,网站重定向到不同的URL,并提供了会话所需的cookie。我已经检查了网站如何“工作”与chrome开发人员工具,我有必要的参数,以便发布。
我的客户目前没有收到所需的Cookie,因为它没有跟进重定向。我想知道接下来要做什么。登录后如何跟进服务器重定向,以获取所需的cookie?我应该使用哪些类/方法?我读到了关于htmlUnit但是我想避免使用它,因为库/数据大小很大,我的应用程序只有0.5mb。
我现在在做什么(简化):
连接 - >登录(httpPost) - >成功(200) - >我只收到一个 cookie(不是我需要的那个)。
我认为我应该做的事情(简化):
连接 - >登录 - >成功(200) - >跟进重定向 - > 获取cookie(共5个)
感谢您的时间和这里的代码。我现在使用的cookie是不正确的。
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
Log.d("LOGGING" , "Posting...");
HttpPost httpost = new HttpPost(url);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("user", "myUser"));
nvps.add(new BasicNameValuePair("passwrd", "myPw"));
nvps.add(new BasicNameValuePair("openid_identifier", ""));
nvps.add(new BasicNameValuePair("cookielength", "-1"));
nvps.add(new BasicNameValuePair("hash_passwrd", ""));
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Log.d("LOGGING" , "Getting login response...");
response = httpclient.execute(httpost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
Log.d("LOGGING" , "Login form getStatus: " + response.getStatusLine());
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
Log.d("LOGGING" , "Cookie: " + cookies.toString());
String SESSION_NAME = "PHPSESSID";
String[] sessionValue = cookies.toString().split("value: ");
String[] sessionValue1 = sessionValue[1].split("]");
String realSessionValue = sessionValue1[0].toString();
Log.d("LOGGING", "SESSION NAME:" + realSessionValue);
/*
Connection.Response loginForm = Jsoup.connect(url)
.method(Connection.Method.GET)
.referrer(referrer)
.execute();
Document login = Jsoup.connect(url)
.data("user", "myUser")
.data("passwrd", "myPw")
.data("cookielength", "1440")
.data("openid_identifier", "")
.data("hash_password", "")
.referrer(referrer)
.cookie(SESSION_NAME, realSessionValue)
.post();
*/
doc = Jsoup.connect(url)
.cookie(SESSION_NAME, realSessionValue)
.get();
//String body = doc.select("body").html();
//Log.d("LOGGING", "Body: " + body.toString());
//Check login
Elements bodies = doc.select("body").first().select("div#main-container-radio").first().select("div#radiorow").first().select("div.bghue").first().select("form#shoutbox-form-r");
Log.d("LOGGING", "Login status: " + bodies.toString());
答案 0 :(得分:0)
谢谢大家。这是我自己的代码中的一个问题,我错误地使用了错误的网址,因为他们有3个不同的用于登录。否则它运行得很好。