中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

使用單例模式實現(xiàn)的HttpClient工具類

2018-07-20    來源:open-open

容器云強勢上線!快速搭建集群,上萬Linux鏡像隨意使用

引子

在Android開發(fā)中我們經(jīng)常會用到網(wǎng)絡連接功能與服務器進行數(shù)據(jù)的交互,為此Android的SDK提供了Apache的HttpClient來方便我們使用各種Http服務。你可以把HttpClient想象成一個瀏覽器,通過它的API我們可以很方便的發(fā)出GET,POST請求(當然它的功能遠不止這些)。

比如你只需以下幾行代碼就能發(fā)出一個簡單的GET請求并打印響應結果:

try {
        // 創(chuàng)建一個默認的HttpClient
        HttpClient httpclient =new DefaultHttpClient();
        // 創(chuàng)建一個GET請求
        HttpGet request =new HttpGet("www.google.com");
        // 發(fā)送GET請求,并將響應內(nèi)容轉換成字符串
        String response = httpclient.execute(request, new BasicResponseHandler());
        Log.v("response text", response);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

為什么要使用單例HttpClient?

這只是一段演示代碼,實際的項目中的請求與響應處理會復雜一些,并且還要考慮到代碼的容錯性,但是這并不是本篇的重點。注意代碼的第三行:

HttpClient httpclient =new DefaultHttpClient();

在發(fā)出HTTP請求前,我們先創(chuàng)建了一個HttpClient對象。那么,在實際項目中,我們很可能在多處需要進行HTTP通信,這時候我們不需要為每個請求都創(chuàng)建一個新的HttpClient。因為之前已經(jīng)提到,HttpClient就像一個小型的瀏覽器,對于整個應用,我們只需要一個HttpClient就夠了。看到這里,一定有人心里想,這有什么難的,用單例啊。【拖襁@樣:

publicclass CustomerHttpClient {
    privatestatic HttpClient customerHttpClient;
    
    private CustomerHttpClient() {
    }
    
    publicstatic HttpClient getHttpClient() {
        if(null== customerHttpClient) {
            customerHttpClient =new DefaultHttpClient();
        }
        return customerHttpClient;
    }
}

那么,哪里不對勁呢?或者說做的還不夠完善呢?

多線程!試想,現(xiàn)在我們的應用程序使用同一個HttpClient來管理所有的Http請求,一旦出現(xiàn)并發(fā)請求,那么一定會出現(xiàn)多線程的問題。這就好像我們的瀏覽器只有一個標簽頁卻有多個用戶,A要上google,B要上baidu,這時瀏覽器就會忙不過來了。幸運的是,HttpClient提供了創(chuàng)建線程安全對象的API,幫助我們能很快地得到線程安全的“瀏覽器”。

public class CustomerHttpClient {
    private staticfinal String CHARSET = HTTP.UTF_8;
    private static HttpClient customerHttpClient;

    private CustomerHttpClient() {
    }

    public static synchronized HttpClient getHttpClient() {
        if (null== customerHttpClient) {
            HttpParams params =new BasicHttpParams();
            // 設置一些基本參數(shù)
            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);
            /* 請求超時 */
            HttpConnectionParams.setSoTimeout(params, 4000);
            
            // 設置我們的HttpClient支持HTTP和HTTPS兩種模式
            SchemeRegistry schReg =new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory
                    .getSocketFactory(), 443));

            // 使用線程安全的連接管理來創(chuàng)建HttpClient
            ClientConnectionManager conMgr =new ThreadSafeClientConnManager(
                    params, schReg);
            customerHttpClient =new DefaultHttpClient(conMgr, params);
        }
        return customerHttpClient;
    }
}

在上面的getHttpClient()方法中,我們?yōu)镠ttpClient配置了一些基本參數(shù)和超時設置,然后使用ThreadSafeClientConnManager來創(chuàng)建線程安全的HttpClient。上面的代碼提到了3種超時設置,比較容易搞混,故在此特作辨析。


HttpClient的3種超時說明

/* 從連接池中取連接的超時時間 */
ConnManagerParams.setTimeout(params, 1000);
/* 連接超時 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 請求超時 */
HttpConnectionParams.setSoTimeout(params, 4000);

第一行設置ConnectionPoolTimeout:這定義了從ConnectionManager管理的連接池中取出連接的超時時間,此處設置為1秒。

第二行設置ConnectionTimeout: 這定義了通過網(wǎng)絡與服務器建立連接的超時時間。Httpclient包中通過一個異步線程去創(chuàng)建與服務器的socket連接,這就是該socket連接的超時時間,此處設置為2秒。

第三行設置SocketTimeout: 這定義了Socket讀數(shù)據(jù)的超時時間,即從服務器獲取響應數(shù)據(jù)需要等待的時間,此處設置為4秒。

以上3種超時分別會拋出ConnectionPoolTimeoutException,ConnectionTimeoutException與SocketTimeoutException。

封裝簡單的POST請求

有了單例的HttpClient對象,我們就可以把一些常用的發(fā)出GET和POST請求的代碼也封裝起來,寫進我們的工具類中了。目前我僅僅實現(xiàn)發(fā)出POST請求并返回響應字符串的方法以供大家參考。將以下代碼加入我們的CustomerHttpClient類中:

privatestaticfinal String TAG ="CustomerHttpClient";

publicstatic String post(String url, NameValuePair... params) {
        try {
            // 編碼參數(shù)
            List<NameValuePair> formparams =new ArrayList<NameValuePair>(); // 請求參數(shù)
for (NameValuePair p : params) {
                formparams.add(p);
            }
            UrlEncodedFormEntity entity =new UrlEncodedFormEntity(formparams,
                    CHARSET);
            // 創(chuàng)建POST請求
            HttpPost request =new HttpPost(url);
            request.setEntity(entity);
            // 發(fā)送請求
            HttpClient client = getHttpClient();
            HttpResponse response = client.execute(request);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                thrownew RuntimeException("請求失敗");
            }
            HttpEntity resEntity =  response.getEntity();
            return (resEntity ==null) ?null : EntityUtils.toString(resEntity, CHARSET);
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, e.getMessage());
            returnnull;
        } catch (ClientProtocolException e) {
            Log.w(TAG, e.getMessage());
            returnnull;
        } catch (IOException e) {
            thrownew RuntimeException("連接失敗", e);
        }

    }


使用我們的CustomerHttpClient工具類

現(xiàn)在,在整個項目中我們都能很方便的使用該工具類來進行網(wǎng)絡通信的業(yè)務代碼編寫了。下面的代碼演示了如何使用username和password注冊一個賬戶并得到新賬戶ID。

final String url ="http://yourdomain/context/adduser";
    //準備數(shù)據(jù)
    NameValuePair param1 =new BasicNameValuePair("username", "張三");
    NameValuePair param2 =new BasicNameValuePair("password", "123456");
    int resultId =-1;
    try {
        // 使用工具類直接發(fā)出POST請求,服務器返回json數(shù)據(jù),比如"{userid:12}"
        String response = CustomerHttpClient.post(url, param1, param2);
        JSONObject root =new JSONObject(response);
        resultId = Integer.parseInt(root.getString("userid"));
        Log.i(TAG, "新用戶ID:"+ resultId);
    } catch (RuntimeException e) {
        // 請求失敗或者連接失敗
        Log.w(TAG, e.getMessage());
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
    } catch (Exception e) {
        // JSon解析出錯
        Log.w(TAG, e.getMessage());
    }


結語

可以看到,使用工具類能大大提高在項目中編寫網(wǎng)絡通信代碼的效率。不過該工具類還有待完善,歡迎各位補充和矯正錯誤,希望最后能完成一個工具類作為使用HttpClient的最佳實踐。(完)


標簽: Google linux ssl 安全 代碼 服務器 通信 網(wǎng)絡

版權申明:本站文章部分自網(wǎng)絡,如有侵權,請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:Python ftp client 處理含有中文的文件名

下一篇:JS判斷字符串長度的5個方法