Android API 14 - 网络操作/ AsyncTask

时间:2011-12-11 14:34:41

标签: android sdk

我最近提出了一个问题,基于使用POST数据执行HTTP请求(在此处找到:Android API 14 - POST Data to HTTP),我被告知我需要尝试类似AsyncTask的东西,因为我无法在主要执行网络操作线程。

简而言之,我不知道该怎么做。任何帮助表示赞赏!这是我的代码:

package me.babblebox.application;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class BabbleBoxActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void check_login() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://babblebox.me/android/test.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
            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
        }
    }
    public void check_login_button(View v) {
           check_login();
    }
}

2 个答案:

答案 0 :(得分:1)

了解Processes and threads AsyncTask

以下内容远非完美,但你可以尝试这样的事情来开始...

public class BabbleBoxActivity extends Activity {

    // Leave onCreate() as it is

    public void check_login_button(View v) {
        PostTask postTask = new PostTask();
        postTask.execute();
    }

    // EDITED THE LINE BELOW TO INCLUDE 'class'
    private class PostTask extends AsyncTask<Void, Void, Void> {

        // Move the code that was in check_login to the
        // doInBackground method below

        protected Void doInBackground(Void... params) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://babblebox.me/android/test.php");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("id", "12345"));
                nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
                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
            }
            return null;
        }
    }
}

实际上,您需要学习如何将参数传递到AsyncTask并让它返回有效结果。

编辑:

出于兴趣,我把原始代码放在一起(没有AsyncTask但在Android v2.2上允许在主线程上进行网络操作)。我添加了一些日志代码只是为了检查连接是否正常...

HttpResponse response = httpclient.execute(httppost);
Header[] headers = response.getAllHeaders();
Log.d("BabbleBox", "Header count: " + headers.length);
for (int c = 0; c < headers.length; c++)
    Log.d("Babblebox", "Header: name=" + headers[c].getName() + " value=" + headers[c].getValue());

...我得到了以下响应标头。

Header count: 6
Header: name=Date value=Sun, 11 Dec 2011 16:38:19 GMT
Header: name=Server value=LiteSpeed
Header: name=Connection value=close
Header: name=X-Powered-By value=PHP/5.3.8
Header: name=Content-Type value=text/html
Header: name=Content-Length value=4

来自任何网络“请求”(GET,POST,PUT)的响应将根据您正在与之通话的远程服务而有所不同。您需要确定服务器要返回的内容,然后相应地处理响应。

答案 1 :(得分:1)

如果您不想AsyncTask(无论出于何种原因),您可能会做类似的事情

public void checkLoginAsync() {

   Executors.newSingleThreadExecutor(new Runnable(){
            @Override
            public void run() {
                  checkLogin();
   });
}

你可能会让checkLogin()接受一些kad的监听器,然后它会报告onLoginErroronLoginSucess之类的内容,比如你实现该监听器的活动。或者也许是你的应用程序,所以你可以说,无论当前显示什么活动,终止程序。