編輯:關於Android編程
public class MyHttpClient { private static final String CHARSET = HTTP.UTF_8; private static HttpClient mClient ; private MyHttpClient(){ } public static synchronized HttpClient getInstance(){ if(null == mClient){ HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, CHARSET) ; HttpProtocolParams.setUseExpectContinue(params, true); HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " +"AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1"); ConnManagerParams.setTimeout(params, 1000);//從連接池中取連接超時的超時時間 HttpConnectionParams.setConnectionTimeout(params, 2000);// http連接超時 HttpConnectionParams.setSoTimeout(params, 4000);// 請求超時時間 SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http",SSLSocketFactory.getSocketFactory(),80)); schReg.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443)); // 使用線程安全來連接管理創建HttpClient對象 ClientConnectionManager conManager = new ThreadSafeClientConnManager(params,schReg); mClient = new DefaultHttpClient(conManager,params); } return mClient ; } public static synchronized void closeHttpClient() { if(mClient != null) { mClient.getConnectionManager().shutdown(); mClient = null; } } }
在用的時候:
public void connectBaiDu(){ HttpClient client = MyHttpClient.getInstance(); try { URI uri = new URI("http://www.baidu.com"); HttpGet get = new HttpGet(uri); HttpResponse response = client.execute(get); if(null == response){ Log.e("", "response is null"); return ; } int statusCode = response.getStatusLine().getStatusCode() ; if(statusCode != HttpStatus.SC_OK ){ return ; } Header[] headers = response.getAllHeaders(); for(Header header : headers){ Log.e("",header.getName() + "-----" + header.getValue()); } InputStream in = response.getEntity().getContent(); if(null == in){ Log.e("", "in is null"); return ; } BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = "" ; while(null != (line = reader.readLine())){ Log.e("line = ",line); } } catch (Exception e) { Log.e("","exception"); e.printStackTrace(); }finally{ MyHttpClient.closeHttpClient(); } }
通過單例模式獲取一個實例,並且執行HttpGet對象,可以從官方文檔中看到,execute方法可以執行很多種的http請求,包括HttpGet,HttpPost,HttpHost,HttpUriRequest等等 比較這兩種方式,當一個應用程序需要很多http請求的時候,使用HttpURLConntection時,http設置或賦初值過於分散,修改是件麻煩事,沒有使用HttpClient方便。當然,你的HttpURLConnection也可以寫成單例模式,但是你得傳入一個URL才能初始化它,相對於HttpClient來說的話類的封裝上就差一些,甚至於沒有必要那樣去寫。這裡要看項目有多大,使用http訪問的多不多,多的話,使用HttpClient構成單例類,要好點。使用的少的話,使用HttpURLConnection要好點。
先看下最終的效果 開始實現新建一個ClockView集成View public class ClockView extends View { }先重寫onM
第一步,在Eclipse中選擇需要打包的項目,然後右鍵--選擇Export,會彈出一個打包的提示框,如下圖所示。按Next之後,會繼續出現一個提示框,這裡你可以選擇自己需
一、實現效果圖關於貝塞爾曲線 二、實現代碼1.自定義viewpackage com.czhappy.showintroduce.view;import android.c
最近在研究AMS代碼遇到一個問題,在函數startActivityUncheckedLocked中 Slog.d("DDY", "!!