Android Http网络请求封装

1.先写一个接口OnHttpRequest.java,用来回调

package com.jandar.http;



public interface OnHttpRequest {
	

	
	/**
	 * 执行加载之前会先判断是否有网络,若无网络则此方法被回调
	 */
	public void httpNoInternet();

	
	
	/**
	 * 开始加载时回调此方法,可在此处设置进度条
	 */
	public void httpStartLoad();
	
	
	
	/**
	 * 加载出错时回调,例如服务器未开启,加载超时等错误
	 */
	public void httpError();
	
	
	
	
	/**
	 * 返回请求结果
	 */
	public void httpResult(String result);
	
	
}

2. 再封装HttpHandler类


package com.jandar.http;

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

public class HttpHandler extends Handler {

	private OnHttpRequest request;
	
	public static final int HTTP_NO_INTERNET = 100;
	public static final int HTTP_START = 101;
	public static final int HTTP_ERROR = 102;
	public static final int HTTP_COMPLETE = 103;

	public HttpHandler(OnHttpRequest request) {
		this.request = request;
	}

	@Override
	public void handleMessage(Message msg) {
		

		if (request == null) {
			return;
		}

		switch (msg.what) { 
		case HTTP_NO_INTERNET:
			request.httpNoInternet();
			break;
		case HTTP_START:
			request.httpStartLoad();
			break;
		case HTTP_ERROR:
			request.httpError();
			break;
		case HTTP_COMPLETE:
			request.httpResult(msg.obj.toString());
			break;
		}

	}

}
3. 写公共Activity类,用于子类继承

package com.jandar.ui;

import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Message;

import com.jandar.http.HttpHandler;
import com.jandar.http.OnHttpRequest;

public class BaseActivity extends Activity {

	private HttpHandler handler;

	protected void setOnHttpRequest(OnHttpRequest request) {
		handler = new HttpHandler(request);
	}

	protected void getResult(final String url) {

		new Thread() {

			@Override
			public void run() {
				if (!isConnected()) {
					handler.sendEmptyMessage(HttpHandler.HTTP_NO_INTERNET);
					return;
				}

				handler.sendEmptyMessage(HttpHandler.HTTP_START);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				try {
					HttpResponse response = client.execute(get);

					InputStream is = response.getEntity().getContent();

					if (is == null) {
						handler.sendEmptyMessage(HttpHandler.HTTP_ERROR);
						return;
					}

					StringBuilder builder = new StringBuilder();
					byte[] buffer = new byte[1024];
					int index = -1;
					while ((index = is.read(buffer)) != -1) {
						builder.append(new String(buffer, 0, index));
					}
					is.close();
					handler.sendMessage(Message.obtain(handler, HttpHandler.HTTP_COMPLETE,
							builder.toString()));
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(HttpHandler.HTTP_ERROR);
				}
			}

		}.start();

	}

	// 判断是否存在网络
	private boolean isConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm != null) {
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

}

4. 最后写测试Activity,xml布局文件比较简单,就不贴了

package com.jandar.test;


import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jandar.http.OnHttpRequest;
import com.jandar.puke.R;
import com.jandar.ui.BaseActivity;

public class MainActivity extends BaseActivity implements OnClickListener, OnHttpRequest {
	private TextView _text;
	private EditText _edit;
	private Button _button;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		context = this;

		initXML();
		
	}

	private void initXML() {
		_text = (TextView) findViewById(R.id.text);
		_edit = (EditText) findViewById(R.id.edit);
		_button = (Button) findViewById(R.id.button);
		_button.setOnClickListener(this);
		
		setOnHttpRequest(this);
	}

	@Override
	public void onClick(View v) {
		getResult("http://www.baidu.com");
	}
	

	@Override
	public void httpNoInternet() {
		_text.setText("当前无网络连接..");
	}

	@Override
	public void httpStartLoad() {
		_text.setText("正在加载,请稍候..");
	}

	@Override
	public void httpError() {
		_text.setText("加载出错了..");
	}

	@Override
	public void httpResult(String result) {
		_text.setText("处理的结果是: \n" + result);
	}
	

}
核心思想就是通过java的接口回调机制来解决Android的非UI线程不能更新UI的问题


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值