POST请求到Web服务器android

时间:2013-01-19 23:34:00

标签: android android-asynctask http-post

我正在使用AsyncTask的应用程序。我正在尝试连接到我的网站,检查用户登录详细信息,如果用户存在则返回true,如果未找到则返回false。根据响应,我将显示错误消息或为用户加载相关屏幕。

但是我想知道下面的代码是应该放在我的登录按钮的onClick监听器中还是放在AsyncTask的onPreExecute()方法中?

我像这样调用asyncTask

public void onClick(View v) {
            //Call background task
            new HttpTask().execute(url);
        }
    });

我在哪里拨打以下代码是否重要?理想情况下它应该在onPreExecute()方法中吗?

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/checklogindetails.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("username", name));
    nameValuePairs.add(new BasicNameValuePair("password", pass));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

感谢有关此人的任何信息。这不是一个问题,对我来说这更像是一个学习曲线,我很好奇我应该做些什么。

感谢。

1 个答案:

答案 0 :(得分:4)

您的HTTP代码需要使用doInBackground()方法,否则它仍然在主(UI)线程中运行,并且可能导致新Android版本的异常(更不用说如果您的请求需要很长时间的锁定)。

这是一个例子(注意构造函数的添加)我决定将对保持在doInBackground()内。由于你没有给我们所有的代码,这可能不会立即起作用。

public class LoginTask extends AsyncTask <String, Void, Boolean>{

  private String name = "", pass= "";
  public LoginTask (String name, String pass )
  {
    super();
    this.name = name;
    this.pass = pass;
  }
  @Override
  protected Boolean  doInBackground (String...url)
  { 
    boolean good = true;

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url[0]);

    try {
      // Add your data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
      nameValuePairs.add(new BasicNameValuePair("username", name));
      nameValuePairs.add(new BasicNameValuePair("password", pass));
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);


    } catch (ClientProtocolException e) {
      good = false;
    } catch (IOException e) {
      good = false;
    }
    return good;
  }

  @Override
  protected void onPostExecute (Boolean result)
  {
    Toast.makeText(MainActivity.this, result ? "Logged in": "Problem", Toast.LENGTH_SHORT).show();
  }
}

你打电话使用

public void onClick(View v) {
            //Call background task
            new HttpTask("myusername", "mypassword").execute(url);
        }
    });