Android中封裝Http請求



HttpConnectionUtils 支持get post put delete請求 圖片請求

 

 

Java代碼 複製代碼 收藏代碼
  1. /** 
  2.  * HTTP connection helper 
  3.  * @author 
  4.  * 
  5.  */  
  6. public class HttpConnectionUtils implements Runnable {  
  7.     private static final String TAG = HttpConnectionUtils.class.getSimpleName();  
  8.     public static final int DID_START = 0;  
  9.     public static final int DID_ERROR = 1;  
  10.     public static final int DID_SUCCEED = 2;  
  11.   
  12.     private static final int GET = 0;  
  13.     private static final int POST = 1;  
  14.     private static final int PUT = 2;  
  15.     private static final int DELETE = 3;  
  16.     private static final int BITMAP = 4;  
  17.   
  18.     private String url;  
  19.     private int method;  
  20.     private Handler handler;  
  21.     private List<NameValuePair> data;  
  22.   
  23.     private HttpClient httpClient;  
  24.   
  25.     public HttpConnectionUtils() {  
  26.         this(new Handler());  
  27.     }  
  28.   
  29.     public HttpConnectionUtils(Handler _handler) {  
  30.         handler = _handler;  
  31.     }  
  32.       
  33.     public void create(int method, String url, List<NameValuePair> data) {  
  34.         Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);  
  35.         this.method = method;  
  36.         this.url = url;  
  37.         this.data = data;  
  38.         ConnectionManager.getInstance().push(this);  
  39.     }  
  40.   
  41.     public void get(String url) {  
  42.         create(GET, url, null);  
  43.     }  
  44.   
  45.     public void post(String url, List<NameValuePair> data) {  
  46.         create(POST, url, data);  
  47.     }  
  48.       
  49.     public void put(String url, List<NameValuePair> data) {  
  50.         create(PUT, url, data);  
  51.     }  
  52.   
  53.     public void delete(String url) {  
  54.         create(DELETE, url, null);  
  55.     }  
  56.   
  57.     public void bitmap(String url) {  
  58.         create(BITMAP, url, null);  
  59.     }  
  60.   
  61.     @Override  
  62.     public void run() {  
  63.         handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));  
  64.         httpClient = new DefaultHttpClient();  
  65.         HttpConnectionParams  
  66.                 .setConnectionTimeout(httpClient.getParams(), 6000);  
  67.         try {  
  68.             HttpResponse response = null;  
  69.             switch (method) {  
  70.             case GET:  
  71.                 response = httpClient.execute(new HttpGet(url));  
  72.                 break;  
  73.             case POST:  
  74.                 HttpPost httpPost = new HttpPost(url);  
  75.                 httpPost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));  
  76.                 response = httpClient.execute(httpPost);  
  77.                 break;  
  78.             case PUT:  
  79.                 HttpPut httpPut = new HttpPut(url);  
  80.                 httpPut.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));  
  81.                 response = httpClient.execute(httpPut);  
  82.                 break;  
  83.             case DELETE:  
  84.                 response = httpClient.execute(new HttpDelete(url));  
  85.                 break;  
  86.             case BITMAP:  
  87.                 response = httpClient.execute(new HttpGet(url));  
  88.                 processBitmapEntity(response.getEntity());  
  89.                 break;  
  90.             }  
  91.             if (method < BITMAP)  
  92.                 processEntity(response.getEntity());  
  93.         } catch (Exception e) {  
  94.             handler.sendMessage(Message.obtain(handler,  
  95.                     HttpConnectionUtils.DID_ERROR, e));  
  96.         }  
  97.           ConnectionManager.getInstance().didComplete(this);  
  98.     }  
  99.   
  100.     private void processEntity(HttpEntity entity) throws IllegalStateException,  
  101.             IOException {  
  102.         BufferedReader br = new BufferedReader(new InputStreamReader(entity  
  103.                 .getContent()));  
  104.         String line, result = "";  
  105.         while ((line = br.readLine()) != null)  
  106.             result += line;  
  107.         Message message = Message.obtain(handler, DID_SUCCEED, result);  
  108.         handler.sendMessage(message);  
  109.     }  
  110.   
  111.     private void processBitmapEntity(HttpEntity entity) throws IOException {  
  112.         BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);  
  113.         Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());  
  114.         handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));  
  115.     }  
/**
 * 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

 

Java代碼 複製代碼 收藏代碼
  1. public class ConnectionManager {  
  2.     public static final int MAX_CONNECTIONS = 5;  
  3.        
  4.     private ArrayList<Runnable> active = new ArrayList<Runnable>();  
  5.     private ArrayList<Runnable> queue = new ArrayList<Runnable>();  
  6.   
  7.     private static ConnectionManager instance;  
  8.   
  9.     public static ConnectionManager getInstance() {  
  10.          if (instance == null)  
  11.               instance = new ConnectionManager();  
  12.          return instance;  
  13.     }  
  14.   
  15.     public void push(Runnable runnable) {  
  16.          queue.add(runnable);  
  17.          if (active.size() < MAX_CONNECTIONS)  
  18.               startNext();  
  19.     }  
  20.   
  21.     private void startNext() {  
  22.          if (!queue.isEmpty()) {  
  23.               Runnable next = queue.get(0);  
  24.               queue.remove(0);  
  25.               active.add(next);  
  26.   
  27.               Thread thread = new Thread(next);  
  28.               thread.start();  
  29.          }  
  30.     }  
  31.   
  32.     public void didComplete(Runnable runnable) {  
  33.          active.remove(runnable);  
  34.          startNext();  
  35.     }  
  36.   
  37. }  
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  也可以自己處理

 

Java代碼 複製代碼 收藏代碼
  1. public class HttpHandler extends Handler {  
  2.   
  3.     private Context context;  
  4.     private ProgressDialog progressDialog;  
  5.   
  6.     public HttpHandler(Context context) {  
  7.         this.context = context;  
  8.     }  
  9.   
  10.     protected void start() {  
  11.         progressDialog = ProgressDialog.show(context,  
  12.                 "Please Wait...""processing..."true);  
  13.     }  
  14.   
  15.     protected void succeed(JSONObject jObject) {  
  16.         if(progressDialog!=null && progressDialog.isShowing()){  
  17.             progressDialog.dismiss();  
  18.         }  
  19.     }  
  20.   
  21.     protected void failed(JSONObject jObject) {  
  22.         if(progressDialog!=null && progressDialog.isShowing()){  
  23.             progressDialog.dismiss();  
  24.         }  
  25.     }  
  26.       
  27.     protected void otherHandleMessage(Message message){  
  28.     }  
  29.       
  30.     public void handleMessage(Message message) {  
  31.         switch (message.what) {  
  32.         case HttpConnectionUtils.DID_START: //connection start  
  33.             Log.d(context.getClass().getSimpleName(),  
  34.                     "http connection start...");  
  35.             start();  
  36.             break;  
  37.         case HttpConnectionUtils.DID_SUCCEED: //connection success  
  38.             progressDialog.dismiss();  
  39.             String response = (String) message.obj;  
  40.             Log.d(context.getClass().getSimpleName(), "http connection return."  
  41.                     + response);  
  42.             try {  
  43.                 JSONObject jObject = new JSONObject(response == null ? ""  
  44.                         : response.trim());  
  45.                 if ("true".equals(jObject.getString("success"))) { //operate success  
  46.                     Toast.makeText(context, "operate succeed:"+jObject.getString("msg"),Toast.LENGTH_SHORT).show();  
  47.                     succeed(jObject);  
  48.                 } else {  
  49.                     Toast.makeText(context, "operate fialed:"+jObject.getString("msg"),Toast.LENGTH_LONG).show();  
  50.                     failed(jObject);  
  51.                 }  
  52.             } catch (JSONException e1) {  
  53.                 if(progressDialog!=null && progressDialog.isShowing()){  
  54.                     progressDialog.dismiss();  
  55.                 }  
  56.                 e1.printStackTrace();  
  57.                 Toast.makeText(context, "Response data is not json data",  
  58.                         Toast.LENGTH_LONG).show();  
  59.             }  
  60.             break;  
  61.         case HttpConnectionUtils.DID_ERROR: //connection error  
  62.             if(progressDialog!=null && progressDialog.isShowing()){  
  63.                 progressDialog.dismiss();  
  64.             }  
  65.             Exception e = (Exception) message.obj;  
  66.             e.printStackTrace();  
  67.             Log.e(context.getClass().getSimpleName(), "connection fail."  
  68.                     + e.getMessage());  
  69.             Toast.makeText(context, "connection fail,please check connection!",  
  70.                     Toast.LENGTH_LONG).show();  
  71.             break;  
  72.         }  
  73.         otherHandleMessage(message);  
  74.     }  
  75.   
  76. }  
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.

 

調用的代碼:

 

Java代碼 複製代碼 收藏代碼
  1. private Handler handler = new HttpHandler(LoginActivity.this) {       
  2.     @Override  
  3.     protected void succeed(JSONObject jObject) { //自己處理成功後的操作  
  4.         super.succeed(jObject);  
  5.     } //也可以在這重寫start() failed()方法  
  6. };  
  7.   
  8. private void login() {  
  9.     ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();  
  10.     params.add(new BasicNameValuePair("email", loginEmail.getText().toString()));  
  11.     params.add(new BasicNameValuePair("password", loginPassword.getText().toString()));  
  12.     String urlString = HttpConnectionUtils.getUrlFromResources(LoginActivity.this, R.string.login_url);  
  13.     new HttpConnectionUtils(handler).post(urlString, params);  
  14.   
  15. }


轉自:http://datuo.iteye.com/blog/1094994

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章