Android HttpClient類的使用

一、HttpClient類的介紹

HttpClient是Apache下的一個Java開源項目,其作用是提供了一個高效、靈活、可擴展的處理HTTP請求的Java工具包,是用於Android上進行網絡通信的標準工具。

使用HttpClient可以很方便地在Android應用程序中執行HTTP請求,例如GET、POST等請求,獲取服務器發送的響應和狀態信息。

二、HttpClient請求流程

HttpClient請求的流程主要分為以下幾個步驟:

  1. 創建 HttpClient 實例
  2.     HttpClient httpClient = new DefaultHttpClient();
    
  3. 創建 HttpGet 或 HttpPost 請求對象
  4.     HttpGet httpGet = new HttpGet(url);
        HttpPost httpPost = new HttpPost(url);
    
  5. 設置請求參數
  6.     List<NameValuePair> paramList = new ArrayList<>();
        paramList.add(new BasicNameValuePair("username", "test"));
        paramList.add(new BasicNameValuePair("password", "123456"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
        httpPost.setEntity(entity);
    
  7. 客戶端執行請求操作,並接收服務端返回的響應結果
  8.     HttpResponse httpResponse = httpClient.execute(httpGet);
    

三、HttpClient基本請求

1、GET請求

GET請求通過在URL後添加參數來傳遞參數信息。下面是一個使用HttpClient發送GET請求的例子。

public static String sendHttpGetRequest(String url) {
    String response = "";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                response = EntityUtils.toString(entity, "UTF-8");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

2、POST請求

POST請求通過在請求體中添加參數來傳遞參數信息。下面是一個使用HttpClient發送POST請求的例子。

public static String sendHttpPostRequest(String url, Map<String, String> params) {
    String response = "";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> paramList = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, "UTF-8");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

四、HttpClient高級請求

1、HttpClient連接池

默認情況下,每次HttpClient請求操作都會創建一個新的HttpClient實例,如果在同一個應用程序中進行多次請求,這樣就會導致資源的浪費。因此,在實際開發中可以考慮使用HttpClient連接池來維護一組可用的HttpClient實例,減少資源的浪費。

public class HttpClientPool {
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 5000;

    static {
        connMgr = new PoolingHttpClientConnectionManager();
        connMgr.setMaxTotal(200);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(MAX_TIMEOUT)
                .setConnectTimeout(MAX_TIMEOUT)
                .setConnectionRequestTimeout(MAX_TIMEOUT)
                .build();
    }

    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connMgr)
                .setDefaultRequestConfig(requestConfig)
                .build();
        return httpClient;
    }
}

2、HttpClient攔截器

HttpClient攔截器是一個在請求執行前後對請求進行處理的機制。

攔截器可以在請求執行前添加一些公共屬性,比如請求頭、cookies等。也可以在請求執行成功後對返回的響應結果進行加工處理。

public class HttpHeaderInterceptor implements HttpRequestInterceptor {

    private Map<String, String> header;

    public HttpHeaderInterceptor(Map<String, String> header) {
        this.header = header;
    }

    @Override
    public void process(HttpRequest request, HttpContext context) {
        for (Map.Entry<String, String> entry : header.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }
}

3、HttpClient文件上傳

HttpClient可以通過MultipartEntity來進行文件上傳操作。

public static String uploadFile(String url, Map<String, String> params, File file) {
    String response = "";
    try {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN));
        }
        builder.addPart("filename", new FileBody(file));
        httpPost.setEntity(builder.build());
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/238571.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 12:12
下一篇 2024-12-12 12:12

相關推薦

  • Android ViewPager和ScrollView滑動衝突問題

    Android開發中,ViewPager和ScrollView是兩個常用的控件。但是當它們同時使用時,可能會發生滑動衝突的問題。本文將從多個方面介紹解決Android ViewPa…

    編程 2025-04-28
  • Android如何點擊其他區域收起軟鍵盤

    在Android應用中,當輸入框獲取焦點彈出軟鍵盤後,我們希望能夠點擊其他區域使軟鍵盤消失,以提升用戶體驗。本篇文章將說明如何實現這一功能。 一、獲取焦點並顯示軟鍵盤 在Andro…

    編程 2025-04-28
  • Android Studio HUD 實現指南

    本文將會以實例來詳細闡述如何在 Android Studio 中使用 HUD 功能實現菊花等待指示器的效果。 一、引入依賴庫 首先,我們需要在 build.gradle 文件中引入…

    編程 2025-04-27
  • Android和Vue3混合開發方案

    本文將介紹如何將Android和Vue3結合起來進行混合開發,以及其中的優勢和注意事項。 一、環境搭建 在進行混合開發之前,需要搭建好相應的開發環境。首先需要安裝 Android …

    編程 2025-04-27
  • Android Java Utils 可以如何提高你的開發效率

    Android Java Utils 是一款提供了一系列方便實用的工具類的 Java 庫,可以幫助開發者更加高效地進行 Android 開發,提高開發效率。本文將從以下幾個方面對 …

    編程 2025-04-27
  • Android JUnit測試完成程序自動退出決方法

    對於一些Android JUnit測試的開發人員來說,程序自動退出是一個經常面臨的困擾。下面從多個方面給出解決方法。 一、檢查測試代碼 首先,我們應該仔細檢查我們的測試代碼,確保它…

    編程 2025-04-25
  • Android Activity啟動流程

    一、Activity概述 Android應用程序是由許多Activity組成的。一個Activity代表一個屏幕上的窗口。用戶與應用程序交互時,Activity會接收用戶的輸入並處…

    編程 2025-04-25
  • Android單元測試詳解

    一、單元測試概述 單元測試是指對軟件中的最小可測試單元進行檢查和驗證。在Android開發中,單元測試是非常重要的一環,可以保證代碼的質量、穩定性以及可維護性。 在Android開…

    編程 2025-04-25
  • Android WebView加載本地HTML

    一、介紹 Android WebView是一個內置的瀏覽器,它允許開發人員在應用中嵌入網頁。使用WebView可以輕鬆地在應用程序中顯示本地或遠程的HTML內容。本篇文章將重點講述…

    編程 2025-04-24
  • Android Wakelock詳解

    一、什麼是Android Wakelock? 在Android應用開發中,Wakelock被廣泛應用於保持屏幕或CPU處於喚醒狀態,以便應用程序可以繼續執行後台任務,直到任務完成。…

    編程 2025-04-24

發表回復

登錄後才能評論