我正在尝试登录 Web 服务器,并且代码运行正常,但是当我尝试围绕它构建登录页面时,事情开始出错了。
如果有人想查看任何额外的代码,我正在使用 Eclipse Android 工具中提供的示例登录页面。
如果我从 OnClickHandler 中执行,那么 DefaultHttpClient 似乎就超时了。它不返回任何东西,或者如果它返回,我知道它是错误的“无对等证书”。
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
...设置东西
mAuthTask = new UserLoginTask();
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
if(attemptLogin()){
mAuthTask.execute();
}
}
});
//mAuthTask = new UserLoginTask();
//mAuthTask.execute(); // Works if called from here.
这是相关的 AsyncTask 代码:
public class UserLoginTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
Log.i(TAG,"Thread name (from preexecute) : " + Thread.currentThread().getName());
}
protected String doInBackground(String... urls) {
DefaultHttpClient client = AppHttpClient.getClient();
HttpPost httppost = new HttpPost("https://euw.leagueoflegends.com/user/login");
String result = "";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("name", "exampleusername"));
nameValuePairs.add(new BasicNameValuePair("pass", "blahblah"));
nameValuePairs.add(new BasicNameValuePair("form_id", "user_login"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.i(TAG,"Thread name (passed into doInBackground) : " + urls[0]);
Log.i(TAG,"Thread name (from doInBackground) : " + Thread.currentThread().getName());
HttpResponse response2 = client.execute(httppost);
InputStream in = response2.getEntity().getContent();
//result = readStream(in);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(final String success) {
mAuthTask = null;
showProgress(false);
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}