Python工程師教你如何使用Android HttpClient發送HTTP請求

一、HttpClient簡介

HttpClient是Apache組織發布的開源HTTP客戶端庫,它支持多線程連接、連接池、SSL、Cookie等特性。Python、Java、C#、C++等多個語言都有HttpClient的實現,本文介紹的是在Android平台上使用HttpClient發送HTTP請求。

二、HttpClient使用流程

HttpClient的使用流程大致如下:

// 創建HttpClient對象,設置連接池和Cookie存儲
HttpClient httpClient = new DefaultHttpClient();
httpClient.setConnPoolTimeout(30 * 1000); // 設置連接超時時間
httpClient.setSoTimeout(30 * 1000); // 設置讀取超時時間
httpClient.setCookieStore(new BasicCookieStore()); // 設置Cookie存儲

// 創建Http請求對象
HttpPost httpPost = new HttpPost(url);

// 設置請求參數
List params = new ArrayList();
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpPost);

// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");

上述代碼通過創建HttpClient對象、創建Http請求對象、設置請求參數、執行Http請求、解析響應結果等步驟來發送HTTP請求。

三、發送GET請求

使用HttpClient發送GET請求也比較簡單,只需要使用HttpGet對象替換HttpPost對象,並傳入請求參數即可。

// 創建Http請求對象
HttpGet httpGet = new HttpGet(url + "?param=123");

// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpGet);

// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");

四、發送文件

使用HttpClient發送文件需要使用MultipartEntityBuilder對象,它可以添加文件參數、普通參數,可以設置字元編碼,也可以設置進度監聽器。

// 創建Http請求對象
HttpPost httpPost = new HttpPost(url);

// 創建MultipartEntityBuilder對象,設置字元編碼和進度監聽器
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
        .setCharset(Charset.forName("UTF-8"))
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addPart("file", new FileBody(file, ContentType.DEFAULT_BINARY))
        .addTextBody("param1", "value1", ContentType.create("text/plain", Charset.forName("UTF-8")))
        .addTextBody("param2", "value2", ContentType.create("text/plain", Charset.forName("UTF-8")))
        .setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");

// 設置請求參數
httpPost.setEntity(builder.build());

// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpPost);

// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");

五、發送JSON數據

使用HttpClient發送JSON數據需要使用StringEntity對象,它可以設置字元編碼和Content-Type。

// 創建Http請求對象
HttpPost httpPost = new HttpPost(url);

// 設置請求頭和請求參數
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));

// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpPost);

// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");

六、完整示例代碼

package com.example.httpclientdemo;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView mResultTv;
    private Button mGetBtn;
    private Button mPostBtn;
    private Button mFileBtn;
    private Button mJsonBtn;
    private HttpClient mHttpClient;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mResultTv.setText("GET請求結果:\n" + msg.obj);
                    break;
                case 1:
                    mResultTv.setText("POST請求結果:\n" + msg.obj);
                    break;
                case 2:
                    mResultTv.setText("文件上傳請求結果:\n" + msg.obj);
                    break;
                case 3:
                    mResultTv.setText("JSON請求結果:\n" + msg.obj);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mResultTv = (TextView) findViewById(R.id.result_tv);
        mGetBtn = (Button) findViewById(R.id.get_btn);
        mPostBtn = (Button) findViewById(R.id.post_btn);
        mFileBtn = (Button) findViewById(R.id.file_btn);
        mJsonBtn = (Button) findViewById(R.id.json_btn);

        // 創建HttpClient對象
        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        connectionManager.setMaxTotal(10);
        connectionManager.setDefaultMaxPerRoute(3);
        ConnManagerParams.setTimeout(connectionManager.getParams(), 10000);
        mHttpClient = new DefaultHttpClient(connectionManager);

        mGetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 發送GET請求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = Message.obtain();
                        try {
                            // 創建Http請求對象
                            HttpGet httpGet = new HttpGet("https://www.baidu.com");

                            // 執行Http請求,獲取響應對象
                            HttpResponse response = mHttpClient.execute(httpGet);

                            // 解析響應結果
                            String result = EntityUtils.toString(response.getEntity(), "UTF-8");

                            msg.what = 0;
                            msg.obj = result;
                        } catch (IOException e) {
                            e.printStackTrace();
                            msg.obj = e.getMessage();
                        } finally {
                            mHandler.sendMessage(msg);
                        }
                    }
                }).start();
            }
        });

        mPostBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 發送POST請求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = Message.obtain();
                        try {
                            // 創建Http請求對象
                            HttpPost httpPost = new HttpPost("https://www.baidu.com");

                            // 設置請求參數
                            List params = new ArrayList();
                            params.add(new BasicNameValuePair("username", "test"));
                            params.add(new BasicNameValuePair("password", "123456"));
                            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

                            // 執行Http請求,獲取響應對象
                            HttpResponse response = mHttpClient.execute(httpPost);

                            // 解析響應結果
                            String result = EntityUtils.toString(response.getEntity(), "UTF-8");

                            msg.what = 1;
                            msg.obj = result;
                        } catch (IOException e) {
                            e.printStackTrace();
                            msg.obj = e.getMessage();
                        } finally {
                            mHandler.sendMessage(msg);
                        }
                    }
                }).start();
            }
        });

        mFileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 發送文件請求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = Message.obtain();
                        try {
                            // 創建Http請求對象
                            HttpPost httpPost = new HttpPost("http://www.example.com/upload");

                            // 創建MultipartEntityBuilder對象,設置字元編碼和進度監聽器
                            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                                    .setCharset(Charset.forName("UTF-8"))
                                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                                    .addPart("file", new FileBody(new File("/sdcard/Download/test.jpg"), ContentType.DEFAULT_BINARY))
                                    .addTextBody("name", "test", ContentType.create("text/plain", Charset.forName("UTF-8")))
                                    .setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");

                            // 設置請求參數
                            httpPost.setEntity(builder.build());

                            // 執行Http請求,獲取響應對象
                            HttpResponse response = mHttpClient.execute(httpPost);

                            // 解析響應結果
                            String result = EntityUtils.toString(response.getEntity(), "UTF-8");

                            msg.what = 2;
                            msg.obj = result;
                        } catch (IOException e) {
                            e.printStackTrace();
                            msg.obj = e.getMessage();
                        } finally {
                            mHandler.sendMessage(msg);
                        }
                    }
                }).start();
            }
        });

        mJsonBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 發送JSON請求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = Message.obtain();
                        try {
                            // 創建Http請求對象
                            HttpPost httpPost = new HttpPost("http://www.example.com/json");

                            // 設置請求頭和請求參數
                            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
                            String jsonStr = "{\"name\":\"test\",\"age\":18}";
                            httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));

                            // 執行Http請求,獲取響應對象
                            HttpResponse response = mHttpClient.execute(httpPost);

                            // 解析響應結果
                            String result = EntityUtils.toString(response.getEntity(), "UTF-8");

                            msg.what = 3;
                            msg.obj = result;
                        } catch (IOException e) {
                            e.printStackTrace();
                            msg.obj = e.getMessage();
                        } finally {
                            mHandler.sendMessage(msg);
                        }
                    }
                }).start();
            }
        });
    }
}

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

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

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論