1. 程式人生 > >Android移動開發-使用URLConnection提交請求的實現

Android移動開發-使用URLConnection提交請求的實現

URL的openConnection()方法將返回一個URLConnection物件,該物件表示應用程式和URL之間的通訊連線。程式可以通過URLConnection例項向該URL傳送請求,讀取URL引用的資源。

通常建立一個和URL的連線,併發送請求、讀取此URL引用的資源需要如下幾個步驟:
Step1: 通過呼叫URL物件的openConnection()方法來建立URLConnection物件;
Step2:設定URLConnection的引數和普通請求屬性;
Step3:如果只是傳送GET方式的請求,那麼使用connect方法建立和遠端資源之間的實際連線即可;如果需要傳送POST方式的請求,則需要獲取URLConnection例項對應的輸出流來發送請求引數;
Step4:遠端資源變為可用,程式可以訪問遠端資源的頭欄位,或通過流入流讀取遠端資源的資料。

下面的程式Demo示範瞭如何向Web站點發送GET請求、POST請求,並從Web站點取得響應。該程式中用到一個GET、POST請求的工具類,該類程式碼如下:

  • GetPostUtil.java邏輯程式碼如下:
package com.fukaimei.getposttest;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import
java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * Created by FuKaimei on 2017/10/2. */ public class GetPostUtil { private static final String TAG = "GetPostUtil"; /** * 向指定URL傳送GET方式的請求 * * @param url 傳送請求的URL * @param params 請求引數,請求引數應該是name1=value1 & name2=value2的形式 * @return
URL所代表遠端資源的響應 */
public static String sendGet(String url, String params) { String result = ""; BufferedReader in = null; try { String urlName = url + "?" + params; URL realUrl = new URL(urlName); // 開啟和URL之間的連線 URLConnection conn = realUrl.openConnection(); // 設定通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // 建立實際的連線 conn.connect(); // 獲取所有的響應頭欄位 Map<String, List<String>> map = conn.getHeaderFields(); // 遍歷所有的響應頭欄位 for (String key : map.keySet()) { Log.d(TAG, key + "---->" + map.get(key)); } // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { Log.d(TAG, "傳送GET請求出現異常!" + e); e.printStackTrace(); } finally { // 使用finally塊來關閉輸入流 try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 向指定URL傳送POST方式的請求 * * @param url 傳送請求的URL * @param params 請求引數,請求引數應該是name1=value1 & name2=value2的形式 * @return 所代表遠端資源的響應 */ public static String sendPost(String url, String params) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 開啟和URL之間的連線 URLConnection conn = realUrl.openConnection(); // 設定通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // 傳送POST請求必須設定如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection物件對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 傳送請求引數 out.print(params); // flush輸出流的快取 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { Log.d(TAG, "傳送POST請求出現異常!" + e); e.printStackTrace(); } finally { // 使用finally塊來關閉輸出流、輸入流 try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } }

從上面的程式Demo可以看出,如果需要傳送GET請求,只要呼叫URLConnection的connect()方法去建立實際的連線即可。如果需要傳送POST請求,則需要獲取URLConnection的OutputStream,然後再向網路中輸出請求引數。
提供了上面傳送GET請求、POST請求的工具類之後,接下來就可以在Activity類中通過該工具類傳送請求了。該程式的介面中包含兩個按鈕,一個按鈕用於傳送GET請求,一個按鈕用於傳送POST請求。程式還提供了一個EditText來顯示伺服器的響應。

  • layout/activity_main.xml介面佈局程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/get"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="傳送GET請求" />

        <Button
            android:id="@+id/post"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="傳送POST請求" />
    </LinearLayout>

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffff"
        android:gravity="top"
        android:textColor="#f000"
        android:textSize="16sp" />
</LinearLayout>
  • MainActivity.java邏輯程式碼如下:
package com.fukaimei.getposttest;

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

public class MainActivity extends AppCompatActivity {

    Button get, post;
    TextView show;
    // 代表伺服器響應的字串
    String response;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                // 設定show控制元件伺服器響應
                show.setText(response);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);
        show = (TextView) findViewById(R.id.show);
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        response = GetPostUtil.sendGet("https://www.mi.com/", null);
                        // 傳送訊息通知UI執行緒更新UI元件
                        handler.sendEmptyMessage(0x123);
                    }
                }.start();
            }
        });
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        response = GetPostUtil.sendPost("http://172.xx.xx.xxx:8080/fukaimei/login.jsp", "name=android&pass=123");
                    }
                }.start();
                // 傳送訊息通知UI執行緒更新UI元件
                handler.sendEmptyMessage(0x123);
            }
        });
    }
}

上面程式Demo中用於傳送GET請求、POST請求。從上面的程式碼可以發現,藉助於URLConnection類的幫助,應用程式可以非常方便地與指定站點交換資訊,包括髮送GET請求、POST請求,並獲取網站的響應等。

  • 注意:由於該程式需要訪問網際網路,因此還需要在清單檔案AndroidManifest.xml檔案中授權訪問網際網路的許可權:
<!--  授權訪問網際網路-->
    <uses-permission android:name="android.permission.INTERNET" />
  • Demo程式執行效果介面截圖如下:

這裡寫圖片描述這裡寫圖片描述