我正在尝试通过 http 发布请求发布一些数据,并了解整个过程。我在 android 开发者网站上红色文档,我看过一些 youtube 教程,但我仍然有一些我不熟悉的点。我找到了以下登录示例代码,但它不在 AsyncTask 中。我知道它必须是。但是,当我尝试使用 AsyncTask 执行此操作时,我的参数定义错误并且我被卡住了。如果我想将一些数据传递给 http 服务器上的 .php 脚本,任何人都可以帮助我并解释它是如何工作的吗?这是我的代码:(编辑后,这是我对 AsyncTask 的尝试):
public class AndroidLogin extends Activity implements OnClickListener{
Button ok,back,exit;
TextView result;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_login);
// Login button clicked
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.lbl_result);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_android_login, menu);
return true;
}
private class Login extends AsyncTask <String,String,String>{
@Override
protected String doInBackground(String... params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://www.mysite.com/login.php");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
result.setText("Login successful");
}else
{
Log.w("SENCIDE", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder inputStreamToString(InputStream is);
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
return null;
}
}
public void onClick(View view) {
new Login().execute();
}
}