首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

android中打包http请求

2012-06-28 
android中封装http请求HttpConnectionUtils 支持get post put delete请求 图片请求??/** * HTTP connectio

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);}@Overridepublic 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 startLog.d(context.getClass().getSimpleName(),"http connection start...");start();break;case HttpConnectionUtils.DID_SUCCEED: //connection successprogressDialog.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 successToast.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 errorif(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) {@Overrideprotected 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   谢谢,学习了

热点排行