Android的API 14 - 网络运营/ AsyncTask的 [英] Android API 14 - Network Operations/AsyncTask

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

问题描述

我最近做了立足于做用POST数据HTTP请求(在这里发现了一个问题:的 Android的API 14日 - POST数据到HTTP ),我被告知我需要尝试一些像一个AsyncTask的,因为我无法进行网络运行在主线程

在简短形式,我不知道如何做到这一点。任何帮助AP preciated!这是我的code:

 包me.babblebox.application;

进口java.io.IOException异常;
进口的java.util.ArrayList;
进口的java.util.List;

进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;

进口android.app.Activity;
进口android.os.Bundle;
进口android.view.View;

公共类BabbleBoxActivity延伸活动{
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
    }
    公共无效check_login(){
        //创建一个新的HttpClient和门柱头球
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(http://babblebox.me/android/test.php);

        尝试 {
            //添加数据
            名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
            nameValuePairs.add(新BasicNameValuePair(ID,12345));
            nameValuePairs.add(新BasicNameValuePair(StringData是,你好));
            httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));

            //执行HTTP POST请求
            HTT presponse响应= httpclient.execute(httppost);

        }赶上(ClientProtocolException E){
            // TODO自动生成的catch块
        }赶上(IOException异常E){
            // TODO自动生成的catch块
        }
    }
    公共无效check_login_button(视图v){
           check_login();
    }
}
 

解决方案

阅读有关的进程和线程 AsyncTask的

下面是远远不够完善,但你可以尝试这样的事情就可以开始...

 公共类BabbleBoxActivity延伸活动{

    //留下的onCreate(),因为它是

    公共无效check_login_button(视图v){
        PostTask postTask =新PostTask();
        postTask.execute();
    }

    // EDITED线下要包含'类'
    私有类PostTask扩展的AsyncTask<虚空,虚空,虚空> {

        //将code,这是在check_login到
        下面// doInBackground方法

        保护无效doInBackground(虚空...... PARAMS){

            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httppost =新HttpPost(http://babblebox.me/android/test.php);

            尝试 {
                //添加数据
                名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
                nameValuePairs.add(新BasicNameValuePair(ID,12345));
                nameValuePairs.add(新BasicNameValuePair(StringData是,你好));
                httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));

                //执行HTTP POST请求
                HTT presponse响应= httpclient.execute(httppost);

            }赶上(ClientProtocolException E){
                // TODO自动生成的catch块
            }赶上(IOException异常E){
                // TODO自动生成的catch块
            }
            返回null;
        }
    }
}
 

在现实中,你需要学习如何通过paramaters到的AsyncTask ,并把它返回有效的结果。

编辑:

只是出于兴趣,我整理了一下原来的code(不带AsyncTask的,但是在Android 2.2版,它允许网络运营上主线程)。我加了一些记录code只是为了检查连接的工作...

 的Htt presponse响应= httpclient.execute(httppost);
标题[]头= response.getAllHeaders();
Log.d(BabbleBox,头数:+ headers.length);
对于(INT C = 0;℃下headers.length; C ++)
    Log.d(Babblebox,标题:名称=+标题[C] .getName()+值=+标题[C] .getValue());
 

......,我得到了下面的响应头。

 报头数:6
标题:名称=日期值=孙,2011 16时38分19秒格林尼治标准​​时间12月11日
标题:名称=服务器值=的Litespeed
标题:名称=连接值=关闭
标题:名称= X-Powered-By中值= PHP / 5.3.8
标题:名称=内容类型值= text / html的
标题:名称= Content-Length值= 4
 

从任何网络的要求的响应(GET,POST,PUT)会根据你所谈论到远程服务的不同而不同。你需要制定出你的服务器将返回,然后相应地处理响应。

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

解决方案

Read about Processes and threads also 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;
        }
    }
}

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

EDIT:

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

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天全站免登陆