Android 執行 HTTP POST 請求

與以前的 GET 請求相似,大的區別是傳入的參數和輸出流:java

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {
    TextView textView1;

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

        textView1 = findViewById(R.id.textView1);
        AsyncPostHttp task_post = new AsyncPostHttp();
        task_post.execute("https://www.baidu.com", "text");
    }

    class AsyncPostHttp extends AsyncTask<String, Float, String> {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        @Override
        protected void onPreExecute() {
            // 任務剛開始的時候執行
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                // 設置須要輸出內容的標識,若是須要傳遞給服務器表單數據,那麼此項需爲 true
                connection.setDoOutput(true);
                // 不使用緩存
                connection.setUseCaches(false);
                // 設置 RequestHeader 與 HTTP 的請求方式
                connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");
                // 應該指的是與服務器創建鏈接的最大時間
                connection.setConnectTimeout(1000);
                // 讀取數據的最大時間,這個不要設置得過短,否則會很容易出現超時的異常
                connection.setReadTimeout(6000);
                // 使用 DataOutputStream 進行輸出操做
                DataOutputStream output = new DataOutputStream(connection.getOutputStream());
                // 傳輸的內容格式就如同 URL 的規範同樣(a=1&b=2),最好進行一次 URL 編碼操做
                String content = "param1=" + URLEncoder.encode(params[1], "utf-8");
                output.writeBytes(content);
                // 輸出完記得關
                output.flush();
                output.close();
                // 若是不是正常的請求結果則拋出異常,注意獲取結果的步驟必定要在請求內容給完以後
                if (connection.getResponseCode() != 200) {
                    throw new Exception(connection.getResponseCode() + "," + connection.getResponseMessage());
                }
                // 使用 InputStream 進行接收操做
                InputStream input = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder response = new StringBuilder();
                // 這裏把 reader 中的內容一行行地讀取到 response 中
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                // 返回最終的結果
                return response.toString();
            } catch (Exception ex) {
                // 返回錯誤消息
                return "Http error: " + ex.getMessage();
            } finally {
                // 請求結束後釋放資源
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }

        @Override
        protected void onProgressUpdate(Float... progresses) {
            // 處理進度報告
        }

        @Override
        protected void onPostExecute(String result) {
            // 任務完成就會到此
            textView1.setText(result);
        }

        @Override
        protected void onCancelled() {
            // 主動取消任務
        }
    }
}
相關文章
相關標籤/搜索