Android onPostExecute未从HTTPPost读取结果
我使用以下命令调用PHP脚本以让用户登录:Android onPostExecute未从HTTPPost读取结果,android,Android,我使用以下命令调用PHP脚本以让用户登录: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button log
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new loginClass().execute();
}
});
}
class loginClass extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Logging you in...");
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
loginClass.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
try {
HttpPost httpPost = new HttpPost("http://www.example.com/login.php");
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpConnectionParams.setSoTimeout(httpParameters, 3000);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
EditText uname = (EditText)findViewById(R.id.usernameField);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.passwordField);
String password = pword.getText().toString();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
HttpClient httpClient = new DefaultHttpClient(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.e("log_tag", "Open Connection");
} catch(ConnectTimeoutException e){
Log.e("Timeout Exception: ", e.toString());
result = null;
} catch(SocketTimeoutException ste){
Log.e("Timeout Exception: ", ste.toString());
result = null;
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
result = null;
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
is.close();
result=sb.toString();
Log.e("log_tag", "Result: "+result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
result = null;
}
return null;
}
protected void onPostExecute(Void v) {
Log.e("log_tag", "Execute Started - Result: "+result);
if (result == null){
this.progressDialog.dismiss();
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Connection Error");
alertDialog.setMessage("There was a problem with your connection.");
alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setButton2("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new loginClass().execute();
}
});
alertDialog.show();
}else if("0".equals(result.toString())){
this.progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Invalid Username/Password. Please try again.", Toast.LENGTH_SHORT).show();
}else if("1".equals(result.toString())){
this.progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
}else{
this.progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Something Else Happened", Toast.LENGTH_SHORT).show();
}
}
}
}
公共类MainActivity扩展活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
按钮登录按钮=(按钮)findViewById(R.id.loginButton);
loginButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
新建loginClass().execute();
}
});
}
类loginClass扩展了异步任务{
private ProgressDialog ProgressDialog=新建ProgressDialog(MainActivity.this);
InputStream=null;
字符串结果=”;
受保护的void onPreExecute(){
setMessage(“登录…”);
progressDialog.show();
progressDialog.setCancelable(假);
progressDialog.setOnCancelListener(新的DialogInterface.OnCancelListener(){
public void onCancel(对话框接口arg0){
loginClass.this.cancel(true);
}
});
}
@凌驾
受保护的Void doInBackground(字符串…参数){
试一试{
HttpPost HttpPost=新的HttpPost(“http://www.example.com/login.php");
HttpParams httpParameters=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
HttpConnectionParams.setSoTimeout(httpParameters,3000);
List nameValuePairs=新的ArrayList(2);
EditText uname=(EditText)findViewById(R.id.usernameField);
字符串username=uname.getText().toString();
EditText pword=(EditText)findViewById(R.id.passwordField);
字符串密码=pword.getText().toString();
添加(新的BasicNameValuePair(“用户名”,username));
添加(新的BasicNameValuePair(“密码”,password));
HttpClient HttpClient=新的默认HttpClient(httpParameters);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
Log.e(“日志标签”,“开放连接”);
}捕获(ConnectTimeoutException e){
Log.e(“超时异常:,e.toString());
结果=空;
}捕捉(SocketTimeoutException ste){
Log.e(“超时异常:,ste.toString());
结果=空;
}捕获(例外e){
e(“Log_标记”,“http连接错误”+e.toString());
结果=空;
}
试一试{
BufferedReader br=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=”;
而((line=br.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
Log.e(“日志标签”,“结果:+结果”);
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
结果=空;
}
返回null;
}
受保护的void onPostExecute(void v){
Log.e(“Log_标记”,“执行已启动-结果:+Result”);
如果(结果==null){
此.progressDialog.discouse()文件;
AlertDialog AlertDialog=新建AlertDialog.Builder(MainActivity.this.create();
alertDialog.setTitle(“连接错误”);
setMessage(“您的连接有问题。”);
alertDialog.setButton(“退出”,新建DialogInterface.OnClickListener()){
public void onClick(DialogInterface dialog,int which){
完成();
}
});
alertDialog.setButton2(“重试”,新建DialogInterface.OnClickListener()){
public void onClick(DialogInterface dialog,int which){
新建loginClass().execute();
}
});
alertDialog.show();
}else如果(“0”.equals(result.toString())){
此.progressDialog.discouse()文件;
Toast.makeText(MainActivity.this,“无效的用户名/密码。请重试。”,Toast.LENGTH_SHORT.show();
}else如果(“1”.equals(result.toString())){
此.progressDialog.discouse()文件;
Toast.makeText(MainActivity.this,“登录成功”,Toast.LENGTH_SHORT.show();
}否则{
此.progressDialog.discouse()文件;
Toast.makeText(MainActivity.this,“发生了其他事情”,Toast.LENGTH_SHORT.show();
}
}
}
}
在LogCat中,我显示了executestarted-Result:0
,但是它没有捕获if语句中的结果,因此最后一个else语句正在触发。“0”.equals(result.toString())
是处理结果的正确方法吗?使用String.contains()
方法
尝试result.toString()包含(“0”)
和result.toString()包含(“1”)
这应该行得通我建议将响应检索为JSON对象,而不是普通的HTTP响应。Ahhaa!成功了。非常感谢你。我打算为此使用JSON,但此时我只需要从登录脚本返回1或0。谢谢我很高兴能帮助杰夫!我发现您只需要0或1,这就是为什么我建议使用
String.contains()
方法而不是