MyException - 我的异常网
当前位置:我的异常网» Android » android中打包http请求

android中打包http请求

www.myexceptions.net  网友分享于:2013-06-29  浏览:26次
android中封装http请求

HttpConnectionUtils 支持get post put delete请求 图片请求

 

 

/**
 * HTTP connection helper
 * @author
 *
 */
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;

	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 HttpConnectionUtils() {
		this(new Handler());
	}

	public HttpConnectionUtils(Handler _handler) {
		handler = _handler;
	}
	
	public void create(int method, String url, List<NameValuePair> data) {
		Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+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() {
		handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));
		httpClient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpClient.getParams(), 6000);
		try {
			HttpResponse response = null;
			switch (method) {
			case GET:
				response = httpClient.execute(new HttpGet(url));
				break;
			case POST:
				HttpPost httpPost = new HttpPost(url);
				httpPost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
				response = httpClient.execute(httpPost);
				break;
			case PUT:
				HttpPut httpPut = new HttpPut(url);
				httpPut.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
				response = httpClient.execute(httpPut);
				break;
			case DELETE:
				response = httpClient.execute(new HttpDelete(url));
				break;
			case BITMAP:
				response = httpClient.execute(new HttpGet(url));
				processBitmapEntity(response.getEntity());
				break;
			}
			if (method < BITMAP)
				processEntity(response.getEntity());
		} catch (Exception e) {
			handler.sendMessage(Message.obtain(handler,
					HttpConnectionUtils.DID_ERROR, e));
		}
		  ConnectionManager.getInstance().didComplete(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, DID_SUCCEED, result);
		handler.sendMessage(message);
	}

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

 

 

ConnectionManager

 

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

}

 

 封装的Handler HttpHandler  也可以自己处理

 

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(JSONObject jObject) {
		if(progressDialog!=null && progressDialog.isShowing()){
			progressDialog.dismiss();
		}
	}

	protected void failed(JSONObject jObject) {
		if(progressDialog!=null && progressDialog.isShowing()){
			progressDialog.dismiss();
		}
	}
	
	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();
			String response = (String) message.obj;
			Log.d(context.getClass().getSimpleName(), "http connection return."
					+ response);
			try {
				JSONObject jObject = new JSONObject(response == null ? ""
						: response.trim());
				if ("true".equals(jObject.getString("success"))) { //operate success
					Toast.makeText(context, "operate succeed:"+jObject.getString("msg"),Toast.LENGTH_SHORT).show();
					succeed(jObject);
				} else {
					Toast.makeText(context, "operate fialed:"+jObject.getString("msg"),Toast.LENGTH_LONG).show();
					failed(jObject);
				}
			} catch (JSONException e1) {
				if(progressDialog!=null && progressDialog.isShowing()){
					progressDialog.dismiss();
				}
				e1.printStackTrace();
				Toast.makeText(context, "Response data is not json data",
						Toast.LENGTH_LONG).show();
			}
			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);
	}

}

 

 我这儿server端返回的数据都是json格式。必须包括{success:"true",msg:"xxx",other:xxx} 操作成功success为true.

 

调用的代码:

 

	private Handler handler = new HttpHandler(LoginActivity.this) {		
		@Override
		protected void succeed(JSONObject jObject) { //自己处理成功后的操作
			super.succeed(jObject);
		} //也可以在这重写start() failed()方法
	};
	
	private void login() {
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("email", loginEmail.getText().toString()));
		params.add(new BasicNameValuePair("password", loginPassword.getText().toString()));
		String urlString = HttpConnectionUtils.getUrlFromResources(LoginActivity.this, R.string.login_url);
		new HttpConnectionUtils(handler).post(urlString, params);
	
	}

 

 

1 楼 sexy22 2012-04-09  
非常不错,呵呵
2 楼 sf_molice 2012-04-10  
连接请求结束后,不用停止该线程吗?
3 楼 sf_molice 2012-04-10  
明了,run运行结束后就自动停止。
4 楼 wenzhixin 2012-06-18  
谢谢,学习了

文章评论

程序员应该关注的一些事儿
程序员应该关注的一些事儿
 程序员的样子
程序员的样子
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
程序员周末都喜欢做什么?
程序员周末都喜欢做什么?
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
如何区分一个程序员是“老手“还是“新手“?
如何区分一个程序员是“老手“还是“新手“?
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
中美印日四国程序员比较
中美印日四国程序员比较
10个调试和排错的小建议
10个调试和排错的小建议
Java程序员必看电影
Java程序员必看电影
旅行,写作,编程
旅行,写作,编程
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
程序员和编码员之间的区别
程序员和编码员之间的区别
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
一个程序员的时间管理
一个程序员的时间管理
科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
漫画:程序员的工作
漫画:程序员的工作
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
十大编程算法助程序员走上高手之路
十大编程算法助程序员走上高手之路
我跳槽是因为他们的显示器更大
我跳槽是因为他们的显示器更大
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
总结2014中国互联网十大段子
总结2014中国互联网十大段子
每天工作4小时的程序员
每天工作4小时的程序员
程序员的鄙视链
程序员的鄙视链
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
老美怎么看待阿里赴美上市
老美怎么看待阿里赴美上市
程序员必看的十大电影
程序员必看的十大电影
Java 与 .NET 的平台发展之争
Java 与 .NET 的平台发展之争
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
编程语言是女人
编程语言是女人
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
代码女神横空出世
代码女神横空出世
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
老程序员的下场
老程序员的下场
鲜为人知的编程真相
鲜为人知的编程真相
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
如何成为一名黑客
如何成为一名黑客
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
那些争议最大的编程观点
那些争议最大的编程观点
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有