編輯:關於Android編程
似乎很久沒有寫博客了,今天看了無意間看了下半年前寫的代碼,設計似乎很有局限性,但基本的通信也算是實現了。
不知道以後看到現在寫的代碼會不會也會有這樣的想法呢?
進入正題,android網絡通信的基本實現的有兩種方式,一種是通過HttpClient來實現,一種是通過HttpURLConnection來實現。
直接上代碼:
首先是一個抽象的http類
/** * 抽象的Http * @author Jenly * @date 2014-8-7 * */ public abstract class AbstractHttp { /** 默認編碼 (UTF-8) */ public static final String DEFAULT_ENCODING = "UTF-8"; /** GET請求時 url和 參數的分隔符 */ public static final String URL_AND_PARA_SEPARATOR = "?"; /** 是否取消請求 */ protected boolean isCancel = false; public static final int DEFAULT_BYTE_LENGTH = 8192; protected static final int LONG_TIME = 0; protected int connectionTimeOut = LONG_TIME; protected int soTimeOut = LONG_TIME; public enum HttpMethod{ /** GET請求 */ GET, /** POST請求 */ POST } /** * 構造 */ public AbstractHttp(){ super(); } public AbstractHttp(int connectionTimeOut,int soTimeOut){ super(); if(connectionTimeOut<0 || soTimeOut <0){ throw new RuntimeException("connectionTimeOut<0 || soTimeOut<0"); } if(connectionTimeOut>0) this.connectionTimeOut = connectionTimeOut; if(soTimeOut>0) this.soTimeOut = soTimeOut; } //----------------------------------------- /** * 取消請求 */ protected void cancel(){ isCancel = true; } /** * 異步線程 * @param runnable */ protected void asyncThread(Runnable runnable){ new Thread(runnable).start(); } /** * 異步連接 默認GET請求 * @param url * @param httpEntity * @param httpCallBack */ public abstract void asyncConnect(String url,HttpCallBackhttpCallBack); /** * 異步連接 默認GET請求 * @param url * @param httpEntity * @param httpCallBack */ public abstract void asyncConnect(String url,Map params,HttpCallBack httpCallBack); /** * 異步連接 * @param url * @param httpEntity * @param httpMethod * @param httpCallBack */ public abstract void asyncConnect(String url,Map params,HttpMethod httpMethod,HttpCallBack httpCallBack); /** * 同步連接 默認GET請求 * @param url * @param httpEntity * @param httpCallBack */ public abstract String syncConnect(String url); /** * 同步連接 默認GET請求 * @param url * @param httpEntity */ public abstract String syncConnect(String url,Map params); /** * 同步連接 默認GET請求 * @param url * @param httpEntity * @param httpMethod */ public abstract String syncConnect(String url,Map params,HttpMethod httpMethod); /** * 同步連接 默認GET請求 * @param url * @param httpEntity * @param httpCallBack */ public abstract String syncConnect(String url,Map params,HttpCallBack httpCallBack); /** * 同步連接 * @param url * @param httpEntity * @param httpMethod * @param httpCallBack */ public abstract String syncConnect(String url,Map params,HttpMethod httpMethod,HttpCallBack httpCallBack); /** * 異步下載文件 * @param url * @param fileName * @param httpDownloadCallBack * @return */ public abstract void asyncDownloadFile(String url,String fileName,HttpCallBack httpDownloadCallBack); /** * 同步下載文件 * @param url * @param fileName * @return */ public abstract File syncDownloadFile(String url,String fileName); /** * 同步下載文件 * @param url * @param fileName * @param httpDownloadCallBack * @return */ public abstract File syncDownloadFile(String url,String fileName,HttpCallBack httpDownloadCallBack); }
/** * Http連接回調接口 * @author Jenly * @date 2014-8-7 */ public interface HttpCallBack{ /** * 開始 * @param url */ void onStart(String url); /** * 加載… * @param progress * @param count */ void onLoading(long progress,long count); /** * 成功 * @param t 返回的對象 */ void onSuccess(T t); /** * 失敗 * @param error * @param e */ void onFailure(String error,Throwable e); /** * 取消 */ void onCancel(); }
/** * Http連接請求回調 * @author Jenly * @date 2014-8-7 */ public abstract class HttpConnectCallBack implements HttpCallBack{ @Override public abstract void onSuccess(String content); }
/** * Http下載回調 * @author Jenly * @date 2014-8-7 */ public abstract class HttpDownloadCallBack implements HttpCallBack{ @Override public abstract void onSuccess(File file); }
/** * Http網絡通信(httpClient實現) * @author Jenly * @date 2014-8-7 */ public class Http extends AbstractHttp{ public Http() { super(); } public Http(int connectionTimeOut, int soTimeOut) { super(connectionTimeOut, soTimeOut); } /** * 獲得一個HttpClient * @return */ private HttpClient getHttpClient(){ HttpParams httpParams = new BasicHttpParams(); if(connectionTimeOut != LONG_TIME && soTimeOut != LONG_TIME){ HttpConnectionParams.setConnectionTimeout(httpParams,connectionTimeOut); HttpConnectionParams.setSoTimeout(httpParams, soTimeOut); } HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams,DEFAULT_BYTE_LENGTH); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager( httpParams, schemeRegistry); return new DefaultHttpClient(threadSafeClientConnManager,httpParams); } /** * 獲得HttpUriRequest * @param url * @param httpMethod * @param params * @return */ private HttpUriRequest getHttpUriRequest(String url,HttpMethod httpMethod,Mapparams){ if(HttpMethod.POST == httpMethod){ HttpPost httpPost = new HttpPost(url); if(params!=null){ List list = new ArrayList (); for(String key : params.keySet()){ list.add(new BasicNameValuePair(key, params.get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(list,DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { LogUtils.e(e); } } return httpPost; }else{ if(params!=null){ List list = new ArrayList (); for(String key : params.keySet()){ list.add(new BasicNameValuePair(key, params.get(key))); } url += URL_AND_PARA_SEPARATOR; url += URLEncodedUtils.format(list,DEFAULT_ENCODING); } LogUtils.v("GET:"+ url); HttpGet httpGet = new HttpGet(url); return httpGet; } } @Override public void asyncConnect(String url,HttpCallBack httpCallBack) { asyncConnect(url, null, HttpMethod.GET, httpCallBack); } @Override public void asyncConnect(String url, Map params,HttpCallBack httpCallBack) { asyncConnect(url, params, HttpMethod.GET, httpCallBack); } @Override public void asyncConnect(final String url,final Map params,final HttpMethod httpMethod,final HttpCallBack httpCallBack) { asyncThread(new Runnable(){ @Override public void run() { syncConnect(url, params,httpMethod, httpCallBack); } }); } @Override public String syncConnect(String url) { return syncConnect(url, null, HttpMethod.GET, null); } @Override public String syncConnect(String url, Map params) { return syncConnect(url, params, HttpMethod.GET, null); } @Override public String syncConnect(String url, Map params,HttpCallBack httpCallBack) { return syncConnect(url, params, HttpMethod.GET, httpCallBack); } @Override public String syncConnect(String url, Map params,HttpMethod httpMethod) { return syncConnect(url, params,httpMethod, null); } @Override public String syncConnect(String url, Map params,HttpMethod httpMethod,HttpCallBack httpCallBack) { if(TextUtils.isEmpty(url)){ return null; } BufferedReader reader = null; HttpClient httpClient = null; int statusCode = -1; try { LogUtils.v(url); if(httpCallBack != null) httpCallBack.onStart(url); HttpUriRequest request = getHttpUriRequest(url,httpMethod,params); httpClient = getHttpClient(); HttpResponse httpResponse = httpClient.execute(request); statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode==HttpStatus.SC_OK){ reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); StringBuffer buffer = new StringBuffer(); String line = null; long progress = 0; long count = httpResponse.getEntity().getContentLength(); isCancel = false; if(httpCallBack != null && count!=-1) httpCallBack.onLoading(progress, count); while ((!isCancel) && (line = reader.readLine())!=null) { buffer.append(line); if(httpCallBack != null && count!=-1){ progress+= line.getBytes().length; httpCallBack.onLoading(progress, count); } } if(httpCallBack != null){ if(!isCancel){ progress = count; httpCallBack.onLoading(progress, count); }else{ reader.close(); httpCallBack.onCancel(); return null; } } reader.close(); if(httpCallBack != null && !isCancel) httpCallBack.onSuccess(buffer.toString()); if(httpClient!=null) httpClient.getConnectionManager().shutdown(); return buffer.toString(); }else{ if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), null); } } catch (ClientProtocolException e) { LogUtils.e(e); if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode),e); } catch (IOException e) { LogUtils.e(e); if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode),e); }catch (Exception e) { LogUtils.e(e); if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode),e); }finally{ if(httpClient!=null) httpClient.getConnectionManager().shutdown(); } return null; } @Override public void asyncDownloadFile(final String url,final String fileName,final HttpCallBack httpDownloadCallBack) { asyncThread(new Runnable() { @Override public void run() { syncDownloadFile(url,fileName,httpDownloadCallBack); } }); } @Override public File syncDownloadFile(String url,String fileName) { return syncDownloadFile(url, fileName, null); } public File syncDownloadFile(String url,String fileName,HttpCallBack httpDownloadCallBack) { if(TextUtils.isEmpty(url)){ return null; } File file = null; BufferedInputStream bis = null; FileOutputStream fos = null; HttpClient httpClient = null; int statusCode = -1; try { LogUtils.v(url); if(TextUtils.isEmpty(fileName)){ return null; } if(httpDownloadCallBack!=null) httpDownloadCallBack.onStart(url); HttpUriRequest httpUriRequest = getHttpUriRequest(url, HttpMethod.GET, null); httpClient = getHttpClient(); HttpResponse httpResponse = httpClient.execute(httpUriRequest); statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK){ file = new File(fileName); fos = new FileOutputStream(file); long progress = 0; long count = httpResponse.getEntity().getContentLength(); bis = new BufferedInputStream(httpResponse.getEntity().getContent()); isCancel = false; byte[] buffer = new byte[DEFAULT_BYTE_LENGTH]; int len = 0; if(httpDownloadCallBack!=null && count!=-1) httpDownloadCallBack.onLoading(progress, count); long time = System.currentTimeMillis(); while((!isCancel) && (len = bis.read(buffer))!=-1){ fos.write(buffer, 0, len); long temp = System.currentTimeMillis(); if(temp-time>=1000){ time = temp; if(httpDownloadCallBack!=null && count!=-1){ progress += len; httpDownloadCallBack.onLoading(progress, count); } } } if(httpDownloadCallBack!=null ){ if(!isCancel){ progress = count; httpDownloadCallBack.onLoading(progress, count); }else{ bis.close(); fos.close(); httpDownloadCallBack.onCancel(); if(httpClient!=null) httpClient.getConnectionManager().shutdown(); return file; } } bis.close(); fos.close(); if(httpDownloadCallBack!=null && !isCancel) httpDownloadCallBack.onSuccess(file);; }else{ if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), null); } } catch (ClientProtocolException e) { LogUtils.e(e); if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), e); e.printStackTrace(); } catch (IOException e) { LogUtils.e(e); if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), e); e.printStackTrace(); }catch (Throwable e) { LogUtils.e(e); if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), e); }finally{ if(httpClient!=null) httpClient.getConnectionManager().shutdown(); } return file; } }
/** * Http網絡通信(HttpURLConnection實現) * @author Jenly * @date 2014-8-7 */ public class KingHttp extends AbstractHttp{ public KingHttp() { super(); } public KingHttp(int connectionTimeOut, int soTimeOut) { super(connectionTimeOut, soTimeOut); } private HttpURLConnection getHttpURLConnection(String url,HttpMethod httpMethod,Mapparams) throws MalformedURLException, IOException{ String paras = null; if(params!=null){ List list = new ArrayList (); for(String key : params.keySet()){ list.add(new BasicNameValuePair(key, params.get(key))); } paras = URLEncodedUtils.format(list, DEFAULT_ENCODING); } if(HttpMethod.GET ==httpMethod && paras!=null){ url += URL_AND_PARA_SEPARATOR; url += paras; } HttpURLConnection httpURLConnection = (HttpURLConnection)new URL(url).openConnection(); httpURLConnection.setConnectTimeout(connectionTimeOut); httpURLConnection.setReadTimeout(soTimeOut); httpURLConnection.setUseCaches(false); if(HttpMethod.POST ==httpMethod){ httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); LogUtils.v("POST:"+ url); if(paras!=null) httpURLConnection.getOutputStream().write(paras.getBytes()); }else{ httpURLConnection.setRequestMethod("GET"); LogUtils.v("GET:"+ url); } return httpURLConnection; } @Override public void asyncConnect(String url, HttpCallBack httpCallBack) { asyncConnect(url, null, httpCallBack); } @Override public void asyncConnect(String url, Map params, HttpCallBack httpCallBack) { asyncConnect(url, params, HttpMethod.GET, httpCallBack); } @Override public void asyncConnect(final String url,final Map params, final HttpMethod httpMethod,final HttpCallBack httpCallBack) { asyncThread(new Runnable() { @Override public void run() { syncConnect(url, params, httpMethod, httpCallBack); } }); } @Override public String syncConnect(String url) { return syncConnect(url, null); } @Override public String syncConnect(String url, Map params) { return syncConnect(url, params, HttpMethod.GET); } @Override public String syncConnect(String url, Map params, HttpMethod httpMethod) { return syncConnect(url, params, httpMethod, null); } @Override public String syncConnect(String url, Map params, HttpCallBack httpCallBack) { return syncConnect(url, params, HttpMethod.GET, httpCallBack); } @Override public String syncConnect(String url, Map params, HttpMethod httpMethod, HttpCallBack httpCallBack) { if(TextUtils.isEmpty(url)){ return null; } BufferedReader reader = null; HttpURLConnection httpURLConnection = null; int statusCode = -1; try { LogUtils.v(url); if(httpCallBack!=null){ httpCallBack.onStart(url); } httpURLConnection = getHttpURLConnection(url,httpMethod,params); httpURLConnection.connect(); statusCode = httpURLConnection.getResponseCode(); if(statusCode==HttpURLConnection.HTTP_OK){ reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); StringBuffer buffer = new StringBuffer(); String line = null; long progress = 0; long count = httpURLConnection.getContentLength(); isCancel = false; if(httpCallBack != null && count!=-1) httpCallBack.onLoading(progress, count); while ((!isCancel) && (line = reader.readLine())!=null) { buffer.append(line); if(httpCallBack != null && count!=-1){ progress+= line.getBytes().length; httpCallBack.onLoading(progress, count); } } if(httpCallBack != null){ if(!isCancel){ progress = count; httpCallBack.onLoading(progress, count); }else{ reader.close(); httpCallBack.onCancel(); return null; } } reader.close(); if(httpCallBack != null && !isCancel) httpCallBack.onSuccess(buffer.toString()); if(httpURLConnection!=null) httpURLConnection.disconnect(); return buffer.toString(); }else{ if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), null); } } catch (MalformedURLException e) { LogUtils.e(e); if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e); } catch (IOException e) { LogUtils.e(e); if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e); } catch (Exception e) { LogUtils.e(e); if(httpCallBack != null) httpCallBack.onFailure(String.valueOf(statusCode), e); }finally{ if(httpURLConnection!=null){ httpURLConnection.disconnect(); } } return null; } @Override public void asyncDownloadFile(final String url,final String fileName, final HttpCallBack httpDownloadCallBack) { asyncThread(new Runnable() { @Override public void run() { syncDownloadFile(url,fileName,httpDownloadCallBack); } }); } @Override public File syncDownloadFile(String url, String fileName) { return syncDownloadFile(url, fileName, null); } @Override public File syncDownloadFile(String url, String fileName, HttpCallBack httpDownloadCallBack) { if(TextUtils.isEmpty(url)){ return null; } File file = null; BufferedInputStream bis = null; FileOutputStream fos = null; HttpURLConnection httpURLConnection = null; int statusCode = -1; try { LogUtils.v(url); if(TextUtils.isEmpty(fileName)){ return null; } if(httpDownloadCallBack!=null) httpDownloadCallBack.onStart(url); httpURLConnection = getHttpURLConnection(url,HttpMethod.GET,null); httpURLConnection.connect(); statusCode = httpURLConnection.getResponseCode(); if(statusCode == HttpURLConnection.HTTP_OK){ file = new File(fileName); fos = new FileOutputStream(file); long progress = 0; long count = httpURLConnection.getContentLength(); bis = new BufferedInputStream(httpURLConnection.getInputStream()); isCancel = false; byte[] buffer = new byte[DEFAULT_BYTE_LENGTH]; int len = 0; if(httpDownloadCallBack!=null && count!=-1) httpDownloadCallBack.onLoading(progress, count); long time = System.currentTimeMillis(); while((!isCancel) && (len = bis.read(buffer))!=-1){ fos.write(buffer, 0, len); long temp = System.currentTimeMillis(); if(temp-time>=1000){ time = temp; if(httpDownloadCallBack!=null && count!=-1){ progress += len; httpDownloadCallBack.onLoading(progress, count); } } } if(httpDownloadCallBack!=null ){ if(!isCancel){ progress = count; httpDownloadCallBack.onLoading(progress, count); }else{ bis.close(); fos.close(); httpDownloadCallBack.onCancel(); if(httpURLConnection!=null) httpURLConnection.disconnect(); return file; } } bis.close(); fos.close(); if(httpDownloadCallBack!=null && !isCancel) httpDownloadCallBack.onSuccess(file);; }else{ if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), null); } } catch (ClientProtocolException e) { LogUtils.e(e); if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), e); } catch (IOException e) { LogUtils.e(e); if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), e); }catch (Throwable e) { LogUtils.e(e); if(httpDownloadCallBack!=null) httpDownloadCallBack.onFailure(String.valueOf(statusCode), e); }finally{ if(httpURLConnection!=null) httpURLConnection.disconnect(); } return file; } }
博主曾經對netty4的helloword很感興趣,也曾單純的寫過一個小小的聊天室java代碼,現在重新來看看,浏覽了這位牛人的博客 點擊去看看 我覺得受益匪淺,故拿來分
剛剛介紹的“偽鎖”僅適用於微信,而微信之外的APP又該如何加密上鎖呢?通過“LockdownPro”這款軟件
前言今天有時間來繼續寫寫屬性動畫。簡介眾所周知,屬性動畫是Android3.0版本開始的,一個東西的推出肯定是有它的道理的,那為什麼前面已經有逐幀和補間動畫了還要推出屬性
開門見山:這裡給出rk 在cameraHAL層的camera數據結構:typedef struct FramInfo{ int phy_addr; int v