android Http异步请求封装

首先封装一个基本的HTTP请求类:
package com.yxks.testrc2.utils;

import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.apache.http.params.HttpConnectionParams;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import static java.net.Proxy.Type.HTTP;

/**
 * Created by Administrator on 2016/12/15.
 */

public class HttpConnectionUtils implements Runnable {
    private static final String TAG = HttpConnectionUtils.class.getSimpleName();
    public static final int DID_START = 0;
    public static final int DID_ERROR = 1;
    public static final int DID_SUCCEED = 2;

    public static final int MSGTYPE_STRING = 0;
    public static final int MSGTYPE_BITMAP = 1;

    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 int timeout = 500;
    private Handler handler;
    Map<String, String> data;

    private HttpURLConnection conn;

    public HttpConnectionUtils() {
        this(new Handler());
    }

    public HttpConnectionUtils(Handler _handler) {
        handler = _handler;
    }

    public void create(int method, String url, Map data, int timeout) {
        Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);
        this.method = method;
        this.url = url;
        this.data = data;
        this.timeout = timeout;
        ConnectionManager.getInstance().push(this);
    }

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

    public void post(String url, Map data, int timeout) {
        create(POST, url, data, timeout);
    }

    public void put(String url, Map data, int timeout) {
        create(PUT, url, data, timeout);
    }

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

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

    private String prepareParam(){
        StringBuffer sb = new  StringBuffer();
        if(null == data) {
            return "";
        }
        if (data.size() <= 0){
            return "";
        } else {
            for (String key : data.keySet()) {
                if(sb.length() < 1) {
                    sb.append(key).append("=" ).append(data.get(key));
                } else {
                    sb.append("&" ).append(key).append( "=" ).append(data.get(key));
                }
            }
            return  sb.toString();
        }
    }

    @Override
    public void run() {
        try {
            URL httpUrl = new URL(url); //创建URL对象
            handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));
            conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setConnectTimeout(this.timeout);//设置连接超时
            switch(this.method) {
                case GET: {
                    conn.setRequestMethod("GET");
                    break;
                }
                case POST: {
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true );
                    conn.setDoOutput(true );
                    //填写参数
                    String paramStr = prepareParam();
                    OutputStream os = conn.getOutputStream();
                    os.write(paramStr.toString().getBytes("utf-8" ));
                    os.close();
                    break;
                }
                case DELETE:{
                    conn.setRequestMethod("DELETE");
                    break;
                }
                case BITMAP:{
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.setUseCaches(true);//使用缓存
                    break;
                }
            }

            conn.connect();
            if (conn.getResponseCode() != conn.HTTP_OK) {
                handler.sendMessage(Message.obtain(handler, DID_ERROR));
            } else {
                if(this.method != BITMAP) {//非图片获取
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line, result = "";
                    while ((line = br.readLine()) != null) {
                        result += line;
                    }
                    Log.i("LoginActivity", "**************response=" + result);
                    Message message = Message.obtain(handler, DID_SUCCEED, MSGTYPE_STRING, 0, result);
                    handler.sendMessage(message);
                } else {
                    Bitmap bitmap=null;
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();

                    Message message = Message.obtain(handler, DID_SUCCEED, MSGTYPE_BITMAP, 0, bitmap);
                    handler.sendMessage(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_ERROR, e));
        } finally {
            if (conn != null) {
                conn.disconnect(); //中断连接
            }
        }

        ConnectionManager.getInstance().didComplete(this);
    }
}
然后封装一个统一进行请求的类:
package com.yxks.testrc2.utils;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/12/15.
 */

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

然后定义一个自己的请求完成处理类:
public class HttpHandler extends Handler {
    private Context context;
    private ProgressDialog progressDialog;

    public HttpHandler(Context context) {
        this.context = context;
    }

    protected void start() {
        progressDialog = ProgressDialog.show(context,
                "Please Wait...", "processing...", true);
    }

    protected void succeed(int MsgType, Object obj) {
        if(progressDialog!=null && progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }

    protected void timeout() {

    }

    protected void otherHandleMessage(Message message){
    }

    public void handleMessage(Message message) {

        switch (message.what) {
            case HttpConnectionUtils.DID_START: //connection start
                Log.d(context.getClass().getSimpleName(),
                        "http connection start...");
                start();
                break;
            case HttpConnectionUtils.DID_SUCCEED: //connection success
                progressDialog.dismiss();
                succeed(message.arg1, message.obj);
                break;
            case HttpConnectionUtils.DID_ERROR: //connection error
                if(progressDialog!=null && progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                Exception e = (Exception) message.obj;
                e.printStackTrace();
                Log.e(context.getClass().getSimpleName(), "connection fail."
                        + e.getMessage());
                Toast.makeText(context, "connection fail,please check connection!",
                        Toast.LENGTH_LONG).show();
                break;
        }
        otherHandleMessage(message);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值