android中Http类的封装

原文地址
http://datuo.iteye.com/blog/1094994
运行效果:
android中Http类的封装_第1张图片
这篇主要是对http网络请求的总结。
http的封装:

  1. 在httpConnection中配置一些连接属性,向handler发送数据。
  2. ConnectionManager中开启线程,进行网络链接。
  3. HttpHandler接收返回的数据并处理。
    在activity中的代码:
public class MainActivity extends Activity {
    private Button button_get;
    private TextView textview;
    // 获取北京天气json数据;
    private static final String url_bj = "http://m.weather.com.cn/atad/101010100.html";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_get = (Button) findViewById(R.id.bt_get);
        textview = (TextView) findViewById(R.id.textview);
        button_get.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new HttpConnection(handler).get(url_bj);
            }
        });
    }

    private Handler handler = new HttpHandler(MainActivity.this) {
        //正在加载中;
        @Override
        protected void onLoading() {
            // TODO Auto-generated method stub
            textview.setText("正在加载中...");
        }
        //请求成功后返回的数据;
        @Override
        protected void onSuccess(JSONObject jObject) {
            // TODO Auto-generated method stub
            if (jObject != null) {
                textview.setText(jObject.toString());
            }
        }
        //返回数据失败的回调;
        @Override
        protected void onFailure(JSONObject jObject) {
            // TODO Auto-generated method stub
            textview.setText(jObject + "");
        }

    };

}

HttpHandler代码,httphandler一个抽象类:onSucess()和onFailure()
两个抽象方法。处于不同状态,返回不同的回调。

public abstract class HttpHandler extends Handler {
    public static final int STATE_START = 0;
    public static final int STATE_ERROR = 1;
    public static final int STATE_SUCCEED = 2;
    private Context context;

    public HttpHandler(Context context) {
        this.context = context;
    }
    //正在连接中
    protected abstract void onLoading();
    //数据返回成功;
    protected abstract void onSuccess(JSONObject jObject);
    //连接失败;
    protected abstract void onFailure(JSONObject jObject);
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
        case STATE_START:
            onLoading();
            break;
        case STATE_SUCCEED:
            Object obj = msg.obj;
            if (obj != null) {
                try {
                    JSONObject json = new JSONObject(obj.toString());
                    onSuccess(json);
                } catch (JSONException e) {
                    onSuccess(null);
                }
            }
        case STATE_ERROR:
            Object e = msg.obj;
            if (e != null) {
                JSONObject json;
                try {
                    json = new JSONObject(e.toString());
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    onFailure(null);
                }
            }
            break;
        }
    }
}

HttpConnection配置get,post等请求。然后发送handler。

public class HttpConnection implements Runnable {
    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 Handler handler;
    private List<NameValuePair> data;

    private HttpClient httpClient;

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

    public HttpConnection(Handler handler) {
        // TODO Auto-generated constructor stub
        this.handler = handler;
    }

    public void create(int method, String url, List<NameValuePair> data) {
        this.method = method;
        this.url = url;
        this.data = data;
        ConnectionManager.getInstance().push(this);
    }

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

    public void post(String url, List<NameValuePair> data) {
        create(POST, url, data);
    }

    public void put(String url, List<NameValuePair> data) {
        create(PUT, url, data);
    }

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

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

    @Override
    public void run() {
        // TODO Auto-generated method stub
        handler.sendMessage(Message.obtain(handler, HttpHandler.STATE_START));
        httpClient = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 6000);
        try {
            HttpResponse response = null;
            switch (method) {
            case GET:
                HttpGet httpGet = new HttpGet(url);
                response = httpClient.execute(httpGet);
                break;

            case POST:
                HttpPost httpPost = new HttpPost();
                httpPost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));

                break;
            case PUT:
                HttpPut httpPut = new HttpPut(url);
                httpPut.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
                response = httpClient.execute(httpPut);
                break;
            }
            if (method < BITMAP) {
                processEntity(response.getEntity());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            handler.sendMessage(Message.obtain(handler,
                    HttpHandler.STATE_ERROR, e));
        }
        ConnectionManager.getInstance().didComlete(this);

    }

    private void processEntity(HttpEntity entity) throws IllegalStateException,
            IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                entity.getContent()));
        String line, result = "";
        while ((line = br.readLine()) != null)
            result += line;
        Message message = Message.obtain(handler, HttpHandler.STATE_SUCCEED, result); 
        handler.sendMessage(message);
    }

}

demo下载地址http://download.csdn.net/detail/androidxiaogang/9215257

你可能感兴趣的:(android,网络)