我想要那样的东西。当用户输入用户名和密码然后点击登录按钮然后执行登录操作然后欢迎用户并转到另一页面时,我有一个按钮和2个文本框。我的代码就像的是:
try {
Connection.Response res = Jsoup.connect("URL")
.data("log", "abcd", "pwd", "12345", "wp-submit", "প্রবেশ", "redirect_to", "url", "testcookie", "1")
.method(Method.POST)
.execute();
Map<String, String> cookies = res.cookies();
Document doc2 = Jsoup
.connect("new_url")
.cookies(cookies)
.get();
s = doc2.text().toString();
t.setText(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
t.setText("no");
}
但登录操作无法成功,此处始终显示“否”。 我怎么能成功地做到这一点?
答案 0 :(得分:0)
我认为这是线程问题。因为您的互联网请求在主UI-Thread上。测试一下:
private class AsyncExecution extends AsyncTask<Void, Void, Void>{
boolean tracker = false;
String s = "";
@Override
protected Void doInBackground(Void... params) {
try {
Connection.Response res = Jsoup.connect("http://www.kuetlive.com/wp-login.php")
.data("log", "abcd", "pwd", "12345", "wp-submit", "প্রবেশ", "redirect_to", "http://www.kuetlive.com/wp-admin/", "testcookie", "1")
.method(Method.POST)
.settimeout(60000)//time set for the connection 1 min
.execute();
Map<String, String> cookies = res.cookies();
Document doc2 = Jsoup
.connect("http://www.kuetlive.com/wp-admin/profile.php")
.cookies(cookies)
.get();
s = doc2.text().toString();
tracker = true;
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("tag", e.toString());
tracker = false;
}
}
--- // } // --- i add this by mistake, delete this
@Override
protected void onPostExecute(Void result) {
if(tracker){
t.setText(s);
}else{
t.setText("no");
}
}
}
并将其命名为
new AsyncExecution().execute();
<强>编辑:强>
你不能在主UI-Thread上执行互联网请求。这就是为什么你需要一个不同的线程。现在你可以实现一个简单的线程,而不是AsyncTask
。那我为什么建议你使用AyncTask
。答案是,您无法从简单的线程更新UI。这就是你需要AsyncTask
的原因,因为AsyncTask
可以灵活地更新UI,但在UI-Thread旁边的不同线程中执行你的方法。