Android Http异步请求,Callback

1 首先是HttpConnection,方法包括HttPost, HttpGet

package com.juupoo.common;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * Asynchronous HTTP connections
 *
 * @author Greg Zavitz & Joseph Roth
 */
public class HttpConnection implements Runnable {

    public static final int DID_START = 0;
    public static final int DID_ERROR = 1;
    public static final int DID_SUCCEED = 2;

    private static final int GET = 0;
    private static final int POST = 1;
    private static final int PUT = 2;
    private static final int DELETE = 3;
    private static final int BITMAP = 4;

    private String url;
    private int method;
    private String data;
    private CallbackListener listener;

    private HttpClient httpClient;

    // public HttpConnection() {
    // this(new Handler());
    // }

    public void create(int method, String url, String data, CallbackListener listener) {
        this.method = method;
        this.url = url;
        this.data = data;
        this.listener = listener;
        ConnectionManager.getInstance().push(this);
    }

    public void get(String url) {
        create(GET, url, null, listener);
    }

    public void post(String url, String data, CallbackListener listener) {
        create(POST, url, data, listener);
    }

    public void put(String url, String data) {
        create(PUT, url, data, listener);
    }

    public void delete(String url) {
        create(DELETE, url, null, listener);
    }

    public void bitmap(String url) {
        create(BITMAP, url, null, listener);
    }

    public interface CallbackListener {
        public void callBack(String result);
    }

    private static final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case HttpConnection.DID_START: {
                    break;
                }
                case HttpConnection.DID_SUCCEED: {
                    CallbackListener listener = (CallbackListener) message.obj;
                    Object data = message.getData();
                    if (listener != null) {
                        if(data != null) {
                            Bundle bundle = (Bundle)data;
                            String result = bundle.getString("callbackkey");
                            listener.callBack(result);
                        }
                    }
                    break;
                }
                case HttpConnection.DID_ERROR: {
                    break;
                }
            }
        }
    };

    public void run() {
//      handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
        httpClient = getHttpClient();
        try {
            HttpResponse httpResponse = null;
            switch (method) {
            case GET:
                httpResponse = httpClient.execute(new HttpGet(
                        StaticInfos.Server_URL + url));
                break;
            case POST:
                HttpPost httpPost = new HttpPost(StaticInfos.Server_URL
                        + url);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                BasicNameValuePair valuesPair = new BasicNameValuePair("args",
                        data);
                params.add(valuesPair);
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                httpResponse = httpClient.execute(httpPost);
                if (isHttpSuccessExecuted(httpResponse)) {
                    String result = EntityUtils.toString(httpResponse
                            .getEntity());
                    this.sendMessage(result);
                } else {
                    this.sendMessage("fail");
                }
                break;
            }
        } catch (Exception e) {
            this.sendMessage("fail");
        }
        ConnectionManager.getInstance().didComplete(this);
    }

    // private void processBitmapEntity(HttpEntity entity) throws IOException {
    // BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    // Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
    // handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
    // }

    private void sendMessage(String result) {
        Message message = Message.obtain(handler, DID_SUCCEED,
                listener);
        Bundle data = new Bundle();
        data.putString("callbackkey", result);
        message.setData(data);
        handler.sendMessage(message);

    }

    public static DefaultHttpClient getHttpClient() {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
        HttpConnectionParams.setSoTimeout(httpParams, 20000);
        // HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

    public static boolean isHttpSuccessExecuted(HttpResponse response) {
        int statusCode = response.getStatusLine().getStatusCode();
        return (statusCode > 199) && (statusCode < 400);
    }

}

2  ConnectionManager类,将线程添加到队列中

package com.juupoo.common;

import java.util.ArrayList;

/**
 * Simple connection manager to throttle connections
 *
 * @author Greg Zavitz
 */
public class ConnectionManager {

    public static final int MAX_CONNECTIONS = 5;

    private ArrayList<Runnable> active = new ArrayList<Runnable>();
    private ArrayList<Runnable> queue = new ArrayList<Runnable>();

    private static ConnectionManager instance;

    public static ConnectionManager getInstance() {
        if (instance == null)
            instance = new ConnectionManager();
        return instance;
    }

    public void push(Runnable runnable) {
        queue.add(runnable);
        if (active.size() < MAX_CONNECTIONS)
            startNext();
    }

    private void startNext() {
        if (!queue.isEmpty()) {
            Runnable next = queue.get(0);
            queue.remove(0);
            active.add(next);

            Thread thread = new Thread(next);
            thread.start();
        }
    }

    public void didComplete(Runnable runnable) {
        active.remove(runnable);
        startNext();
    }

}

3 调用:

new HttpConnection().post("user.login", args, callbackListener);

private CallbackListener callbackListener = new HttpConnection.CallbackListener() {
        @Override
        public void callBack(String v) {
            if(v != "fail") {
                if("false".equals(v)) {
                    LoginActivity.this.showInfo(R.string.username_or_pass_error);
                } else {
                    // 登录
                    Intent intent = new Intent();
                    intent.setClass(LoginActivity.this, MainActivity.class);
                    LoginActivity.this.startActivity(intent);
                }
            } else {
                LoginActivity.this.showInfo(R.string.network_transfer_error);
            }
            progressDialog.dismiss();
        }
    };

可参考本文。

http://masl.cis.gvsu.edu/2010/04/05/android-code-sample-asynchronous-http-connections/

文章出处:http://blog.csdn.net/jkguang/article/details/7028565

时间: 2024-10-29 11:06:00

Android Http异步请求,Callback的相关文章

将已经存在的异步请求callback转换为同步promise

由于js是单线程执行,为防止阻塞,会有很多异步回调函数callback,嵌套层次多了,可读性就差了很多.随着社区的发展,出现了promise.我们来将一些常见的回调函数做修改,变成promise的链式调用,简洁,清晰明了. 先理解一点点概念. 每个promise都有三个状态.pending.Fulfilled.Rejected.最初为pending,状态一但改变为Fulfilled.Rejected中的一种,即成永远,不再改变. pending: 等待状态. Fulfilled: 表示成功完成.

Android简单封装类似JQuery异步请求

在android开发中经常会使用异步请求数据,通常会使用handler或者AsyncTask去做,handler 配合message 使用起来比较麻烦,AsyncTask 线程池只允许128个线程工作,会有溢出的问题,(当然一般情况不会有那么多线程同时工作的)所以写了这个代码,还望高手指正! [Java]代码 01 package com.xbl.task; 02 03 import java.io.BufferedReader; 04 import java.io.InputStream; 0

【Java&amp;Android开源库代码剖析】のandroid-async-http(如何设计一个优雅的Android网络请求框架,同时支持同步和异步请求)开篇

在<[Java&Android开源库代码剖析]のandroid-smart-image-view>一文中我们提到了android-async-http这个开源库,本文正式开篇来详细介绍这个库的实现,同时结合源码探讨如何设计一个优雅的Android网络请求框架.做过一段时间Android开发的同学应该对这个库不陌生,因为它对Apache的HttpClient API的封装使得开发者可以简洁优雅的实现网络请求和响应,并且同时支持同步和异步请求. 网络请求框架一般至少需要具备如下几个组件:1

Android含文档server结束(client UI接口异步请求的一部分)三

在本文中,AsyncTask为了实现异步请求,详细代码如下所示的: public class downloadActivity extends Activity { private TextView myTextView=null; private Button button=null; private static final String path="http://192.168.0.179:8080/Myweb/download.do"; private ProgressDial

android开发-网络请求Ⅰ

本章讲述在android开发中,常用的网络请求操作.网络请求利用android基本的HttpURLConnection连接URL和开源网络请求包AsyncHttpClient.本次网络请求以调取天气接口查询天气为案例,对请求到的天气数据采用SQLite数据库存储,并利用ContentProvider数据共享模式操作存储数据.本章主要介绍知识点HttpURLConnection,AsyncHttpClient,ContentProvider,Json解析插件GsonFormat及Json解析类Gs

libcurl的封装,支持同步异步请求,支持多线程下载,支持https

最近在做一个项目,需要用到http get post等 需求分析需要做到同步和异步,异步请求的返回以可选的回调通知的方式进行. 本人以Linux为例,一步一步的来实现. 配置并且编译libcurl我以在Linux底下的交叉编译举例.libcurl源码下载: http://curl.haxx.se/download.html配置libcurl支持https和zlib压缩,必须需要openssl和zlib库openssl库源码下载: http://www.openssl.org/source/.下载

jQuery基础(Ajax,load(),getJSON(),getScript(),post(),ajax(),同步/异步请求数据)

1.使用load()方法异步请求数据 使用load()方法通过Ajax请求加载服务器中的数据,并把返回的数据放置到指定的元素中,它的调用格式为: load(url,[data],[callback]) 参数url为加载服务器地址,可选项data参数为请求时发送的数据,callback参数为数据请求成功后,执行的回调函数. 2.使用getJSON()方法异步加载JSON格式数据 使用getJSON()方法可以通过Ajax异步请求的方式,获取服务器中的数据,并对获取的数据进行解析,显示在页面中,它的

Ajax异步请求(二)

业精于勤,荒于嬉:行成于思,毁于随. ----致自己 目录: 二.jQuery四种常用的Ajax请求方式简介 1.$.ajax() 2.$.get() 3.$.post() 4.$.getJSON() ==================1.$.ajax()======================== jQuery在异步请求方面封装的较好,直接使用Ajax比较麻烦,jQuery大大简化了我们的使用,不用考虑浏览器之间的差异了. $.ajax()是jQuery底层ajax的实现,$.get()

ajax异步请求

随便写写: 异步请求,相当于只是局部向浏览器发送请求,局部刷新的意思. 请求的方式 有两大类分为get: post. 自己封装的ajax var AjaxHelp = { ///返回创建的异步对象 GetReques: function () { var xlm = new XMLHttpRequest(); return xlm; }, ///异步对象的请求               //请求方式,地址,参数,回调函数 ProcessReques: function (methor, url