Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網絡通訊實戰:GET 請求與 POST 請求

編輯:關於 Android 程式設計

做 Android 開發,網絡數據的抓取與提交是家常便飯。一個簡單的口訣可以幫你快速定位場景:獲取數據用 GET 請求,而新增、刪除、修改、查詢等需要改動服務端數據的操作則用 POST 請求。

整體思路

本例用 HttpURLConnection 完成兩種請求,並借助 AsyncTask 把網絡操作放到子線程,避免阻塞主線程(UI 線程)。GET 直接把參數拼在 URL 後邊;POST 則把參數寫入輸出流,並通過 setRequestMethod("POST") 與適當的請求頭來告知服務端。

Activity 與請求邏輯

點擊「查詢(GET 方法)」按鈕時拼接參數發起 GET;點擊「查詢(POST 方法)」時把參數放進數組交給 POST 任務處理。

public class HttpActivity extends AppCompatActivity {
    public EditText et;
    private Button search;
    private Button search1;
    private TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        et = (EditText) findViewById(R.id.et);
        search = (Button) findViewById(R.id.search);
        search1 = (Button) findViewById(R.id.search1);
        show = (TextView) findViewById(R.id.show);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "https://192.168.1.48:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";
                new MyGetJob().execute(url);
            }
        });

        search1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] arg = new String[2];
                arg[0] = "https://192.168.1.48:8080/HttpTest/index.jsp";
                arg[1] = "option=getUser&uName=jerehedu";
                new MyPostJob1().execute(arg);
            }
        });
    }

    // POST 異步任務
    private class MyPostJob1 extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            HttpURLConnection con = null;
            InputStream is = null;
            StringBuilder sbd = new StringBuilder();
            try {
                URL url = new URL(strings[0]);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(5 * 1000);
                con.setRequestMethod("POST");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setUseCaches(false);
                con.setRequestProperty("Charset", "UTF-8");
                con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                // params 形如:option=getUser&uName=jerehedu
                String params = strings[1];
                OutputStream os = con.getOutputStream();
                os.write(params.getBytes()); // 數據傳輸流
                os.flush();
                os.close();
                if (con.getResponseCode() == 200) {
                    is = con.getInputStream();
                    int next = 0;
                    byte[] b = new byte[1024];
                    while ((next = is.read(b)) > 0) {
                        sbd.append(new String(b, 0, next));
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try { is.close(); } catch (IOException e) { e.printStackTrace(); }
                    if (con != null) { con.disconnect(); }
                }
            }
            return sbd.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            show.setText("POST請求結果:" + s);
        }
    }

    // GET 異步任務
    private class MyGetJob extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            HttpURLConnection con = null;
            InputStream is = null;
            StringBuilder sbd = new StringBuilder();
            try {
                URL url = new URL(strings[0]);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(5 * 1000);
                // 200 成功 / 404 未找到 / 500 服務端錯誤
                if (con.getResponseCode() == 200) {
                    is = con.getInputStream();
                    int next = 0;
                    byte[] bt = new byte[1024];
                    while ((next = is.read(bt)) > 0) {
                        sbd.append(new String(bt, 0, next));
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try { is.close(); } catch (IOException e) { e.printStackTrace(); }
                    if (con != null) { con.disconnect(); }
                }
            }
            return sbd.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            show.setText(s);
        }
    }
}

關於 AsyncTask 的三個泛型參數需要牢記:第一個參數會傳入 doInBackground 方法,第三個參數指定 doInBackground 的返回值類型,而這個返回值會被 onPostExecute 接收並在 UI 線程中處理。

布局文件

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.jreduch07.HttpActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/et"
        android:layout_alignParentStart="true"
        android:layout_alignTop="@+id/et"
        android:text="姓名!"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/search"
        android:layout_centerHorizontal="true"
        android:hint="請輸入要查找姓名" />

    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:text="查詢(GET方法)" />

    <Button
        android:id="@+id/search1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/et"
        android:text="查詢(POST方法)" />

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/search1"
        android:background="#fff30d"
        android:text="查詢結果:"
        android:textSize="30sp" />
</RelativeLayout>

要點回顧

GET 與 POST 在本質上都是基於 HttpURLConnection 的網絡請求,差別在於:GET 把參數附在 URL 之後,讀取輸入流即可拿到結果;POST 需要設置請求方法與 Content-Type 請求頭,並把參數寫入輸出流。同時,別忘了 network 操作一定要放在子線程(這裡用 AsyncTask 封裝),並在 onPostExecute 中回到主線程更新界面。此外,記得在清單文件中申請網絡訪問權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved