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

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值