如何使用AsyncTask类创建Http连接?

时间:2010-02-05 04:50:40

标签: android

我正在尝试使用AsyncTask类创建HTTP连接。

是否可以创建HTTP连接?

您能否提供示例源代码?

提前致谢。

2 个答案:

答案 0 :(得分:13)

作为活动中的内部类:

public final class HttpTask
        extends
        AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {

    private HttpClient mHc = new DefaultHttpClient();

    @Override
    protected String doInBackground(String... params) {
        publishProgress(true);
        // Do the usual httpclient thing to get the result
        return result;
    }

    @Override
    protected void onProgressUpdate(Boolean... progress) {
        // line below coupled with 
        //    getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS) 
        //    before setContentView 
        // will show the wait animation on the top-right corner
        MyActivity.this.setProgressBarIndeterminateVisibility(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        publishProgress(false);
        // Do something with result in your activity
    }

}

然后在你的活动的某个地方:

new HttpTask().execute(someParams...);

答案 1 :(得分:1)