Android API 14 - 网络操作/AsyncTask [英] Android API 14 - Network Operations/AsyncTask

查看:16
本文介绍了Android API 14 - 网络操作/AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently made a question based on doing a HTTP request with POST data (Found here: Android API 14 - POST Data to HTTP) and I was told I would need to try something like an AsyncTask because I cannot carry out Network Operations in the main thread.

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

In short form, I have no idea how to do this. Any help is appreciated! Here is my code:

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();
    }
}

推荐答案

阅读 进程和线程还有AsyncTask.

以下内容远非完美,但您可以尝试这样的方法开始...

The following is far from perfect but you could try something like this to get started...

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 并使其返回有效结果.

In reality you'll need to learn how to pass paramaters into the AsyncTask and get it to return valid results.

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

Just out of interest, I put together your original code (without AsyncTask but on Android v2.2 which allows network operations on main thread). I added some logging code just to check the connection worked...

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());

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

...and I got the following response headers.

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)的响应都会因您正在与之交谈的远程服务而异.您需要计算出您的服务器将返回什么,然后相应地处理响应.

The response from any web 'request' (GET, POST, PUT) will vary depending on the remote service you are talking to. You'll need to work out what your server is going to return and then process the response accordingly.

这篇关于Android API 14 - 网络操作/AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆