Android中封装Http请求
来源:互联网 发布:鹿晗 知乎 编辑:程序博客网 时间:2024/05/17 23:49
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);
- }
转自:http://datuo.iteye.com/blog/1094994
0 0
- Android中封装Http请求
- Android中Http请求类的封装
- Android封装Http请求
- Android Http网络请求封装
- android Http异步请求封装
- Android中Http请求
- Android 封装http请求的工具类
- Android封装的HTTP请求组件
- Android 封装http请求的工具类
- Android 封装http请求的工具类
- Android 封装http请求的工具类
- android 封装Http请求的帮助类
- Android中应对封装好的数据库jar包请求Http数据的结果回调
- Block封装http请求
- http请求封装
- 简单封装 HTTP 请求
- go http 请求封装
- http请求方法封装
- 字符串常量池
- 5张图让你彻底理清数据库 ,数据源和连接池的关系
- poj 2406 Power Strings(kmp)
- 测试android事件分发
- 寻找指定元素的指针
- Android中封装Http请求
- 幸福来敲门观后感
- php和mysql学习之旅
- Julia: 关于Github上的其它库
- Linux安装MySQL的两种方法
- 求两个树结点的最低公共祖先(Again)
- 多态的实现
- zigbee学习之中断led
- Web测试学习资源和主要测试点