Android HTTP請求方式:HttpURLConnection

2023-03-31 14:14 更新

本節(jié)引言:

前面兩節(jié)我們學(xué)習(xí)的都是一些概念性的東西,Http的協(xié)議以及協(xié)議頭的一些東東,而本節(jié)我們 就要堆碼了,而本節(jié)學(xué)習(xí)的是Android為我們提供的Http請求方式之一:HttpURLConnection, 除了這種,還有一種還有一種HttpClient,后者我們會下一節(jié)講!不過前者一旦請求復(fù)雜起來,使用起來 非常麻煩,而后者我們Java抓包也經(jīng)常會用到,是Apache的,畢竟不是谷歌親兒子,而在4.4版本 HttpURLConnection已被替換成OkHttp了!好吧,與時俱進,決定講完HttpClient也來會會這個 OkHttp!對了,一般我們實際開發(fā)并不會用HttpURLConnection和HttpClient,使用別人封裝 好的第三方網(wǎng)絡(luò)請求框架,諸如:Volley,android-async-http,loopj等,因為網(wǎng)絡(luò)操作涉及到 異步以及多線程,自己動手擼的話,很麻煩,所以實際開發(fā)還是直接用第三方??!當然學(xué)習(xí)下也 無妨,畢竟第三方也是在這些基礎(chǔ)上擼起來的,架構(gòu)逼格高,各種優(yōu)化!好的,話不多說,開始 本節(jié)內(nèi)容!


1.HttpURLConnection的介紹

答:一種多用途、輕量極的HTTP客戶端,使用它來進行HTTP操作可以適用于大多數(shù)的應(yīng)用程序。 雖然HttpURLConnection的API提供的比較簡單,但是同時這也使得我們可以更加容易地去使 用和擴展它。繼承至URLConnection,抽象類,無法直接實例化對象。通過調(diào)用openCollection() 方法獲得對象實例,默認是帶gzip壓縮的;


2.HttpURLConnection的使用步驟

使用HttpURLConnection的步驟如下:

  • 創(chuàng)建一個URL對象: URL url = new URL(http://www.baidu.com);
  • 調(diào)用URL對象的openConnection( )來獲取HttpURLConnection對象實例: HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  • 設(shè)置HTTP請求使用的方法:GET或者POST,或者其他請求方式比如:PUT conn.setRequestMethod("GET");
  • 設(shè)置連接超時,讀取超時的毫秒數(shù),以及服務(wù)器希望得到的一些消息頭 conn.setConnectTimeout(6*1000);***conn.setReadTimeout(6 1000);
  • 調(diào)用getInputStream()方法獲得服務(wù)器返回的輸入流,然后輸入流進行讀取了 InputStream in = conn.getInputStream();
  • 最后調(diào)用disconnect()方法將HTTP連接關(guān)掉 conn.disconnect();

PS:除了上面這些外,有時我們還可能需要對響應(yīng)碼進行判斷,比如200: if(conn.getResponseCode() != 200)然后一些處理 還有,可能有時我們 并不需要傳遞什么參數(shù),而是直接去訪問一個頁面,我們可以直接用: final InputStream in = new URL("url").openStream(); 然后直接讀流,不過這個方法適合于直接訪問頁面的情況,底層實現(xiàn)其實也是 return openConnection().getInputStream(),而且我們還不能設(shè)置一些 請求頭的東東,所以要不要這樣寫,你自己要掂量掂量!


3.HttpURLConnection使用示例

這里我們主要針對GET和POST請求寫兩個不同的使用示例,我們可以conn.getInputStream() 獲取到的是一個流,所以我們需要寫一個類將流轉(zhuǎn)化為二進制數(shù)組!工具類如下:

StreamTool.java:

/**
 * Created by Jay on 2015/9/7 0007.
 */
public class StreamTool {
    //從流中讀取數(shù)據(jù)
    public static byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inStream.read(buffer)) != -1)
        {
            outStream.write(buffer,0,len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}

接下來就可以開始擼我們的示例了!


1)HttpURLConnection發(fā)送GET請求代碼示例

運行效果圖

核心部分代碼

布局:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtMenu"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="#4EA9E9"
        android:clickable="true"
        android:gravity="center"
        android:text="長按我,加載菜單"
        android:textSize="20sp" />

    <ImageView
        android:id="@+id/imgPic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">

        <TextView
            android:id="@+id/txtshow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

獲取數(shù)據(jù)類:GetData.java:

/**
 * Created by Jay on 2015/9/7 0007.
 */
public class GetData {
    // 定義一個獲取網(wǎng)絡(luò)圖片數(shù)據(jù)的方法:
    public static byte[] getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 設(shè)置連接超時為5秒
        conn.setConnectTimeout(5000);
        // 設(shè)置請求類型為Get類型
        conn.setRequestMethod("GET");
        // 判斷請求Url是否成功
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("請求url失敗");
        }
        InputStream inStream = conn.getInputStream();
        byte[] bt = StreamTool.read(inStream);
        inStream.close();
        return bt;
    }

    // 獲取網(wǎng)頁的html源代碼
    public static String getHtml(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            byte[] data = StreamTool.read(in);
            String html = new String(data, "UTF-8");
            return html;
        }
        return null;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private TextView txtMenu, txtshow;
    private ImageView imgPic;
    private WebView webView;
    private ScrollView scroll;
    private Bitmap bitmap;
    private String detail = "";
    private boolean flag = false;
    private final static String PIC_URL = "http://ww2.sinaimg.cn/large/7a8aed7bgw1evshgr5z3oj20hs0qo0vq.jpg";
    private final static String HTML_URL = "http://www.baidu.com";

    // 用于刷新界面
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0x001:
                    hideAllWidget();
                    imgPic.setVisibility(View.VISIBLE);
                    imgPic.setImageBitmap(bitmap);
                    Toast.makeText(MainActivity.this, "圖片加載完畢", Toast.LENGTH_SHORT).show();
                    break;
                case 0x002:
                    hideAllWidget();
                    scroll.setVisibility(View.VISIBLE);
                    txtshow.setText(detail);
                    Toast.makeText(MainActivity.this, "HTML代碼加載完畢", Toast.LENGTH_SHORT).show();
                    break;
                case 0x003:
                    hideAllWidget();
                    webView.setVisibility(View.VISIBLE);
                    webView.loadDataWithBaseURL("", detail, "text/html", "UTF-8", "");
                    Toast.makeText(MainActivity.this, "網(wǎng)頁加載完畢", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

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

    private void setViews() {
        txtMenu = (TextView) findViewById(R.id.txtMenu);
        txtshow = (TextView) findViewById(R.id.txtshow);
        imgPic = (ImageView) findViewById(R.id.imgPic);
        webView = (WebView) findViewById(R.id.webView);
        scroll = (ScrollView) findViewById(R.id.scroll);
        registerForContextMenu(txtMenu);
    }

    // 定義一個隱藏所有控件的方法:
    private void hideAllWidget() {
        imgPic.setVisibility(View.GONE);
        scroll.setVisibility(View.GONE);
        webView.setVisibility(View.GONE);
    }

    @Override
    // 重寫上下文菜單的創(chuàng)建方法
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflator = new MenuInflater(this);
        inflator.inflate(R.menu.menus, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    // 上下文菜單被點擊是觸發(fā)該方法
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.one:
                new Thread() {
                    public void run() {
                        try {
                            byte[] data = GetData.getImage(PIC_URL);
                            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        handler.sendEmptyMessage(0x001);
                    }

                    ;
                }.start();
                break;
            case R.id.two:
                new Thread() {
                    public void run() {
                        try {
                            detail = GetData.getHtml(HTML_URL);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        handler.sendEmptyMessage(0x002);
                    };
                }.start();
                break;
            case R.id.three:
                if (detail.equals("")) {
                    Toast.makeText(MainActivity.this, "先請求HTML先嘛~", Toast.LENGTH_SHORT).show();
                } else {
                    handler.sendEmptyMessage(0x003);
                }
                break;
        }
        return true;
    }
}

注意事項

用handler的原因就不用講了吧~ 另外我們加載html代碼的使用的是webView的loadDataWithBaseURL而非LoadData, 如果用LoadData又要去糾結(jié)中文亂碼的問題,so…用loadDataWithBaseURL就可以不用糾結(jié)那么多了 另外有些頁面可能需要我們提交一些參數(shù),比如賬號密碼:我們只需把對應(yīng)參數(shù)拼接到url尾部即可,比如: http://192.168.191.1:8080/ComentServer/LoginServlet?passwd=123&name=Jack 然后服務(wù)端getParamater("passwd")這樣就可以獲得相應(yīng)的參數(shù)了,我們請求時這些東西都會看得清清楚楚 ,所以說GET方式并不安全!另外還有一點要注意的就是Android從4.0開始就不允許在非UI線程中進行UI操作!


2)HttpURLConnection發(fā)送POST請求代碼示例

有GET自然有POST,我們通過openConnection獲取到的HttpURLConnection默認是進行Get請求的, 所以我們使用POST提交數(shù)據(jù),應(yīng)提前設(shè)置好相關(guān)的參數(shù):conn.setRequestMethod("POST"); 還有:conn.setDoOutput(true);conn.setDoInput(true);設(shè)置允許輸入,輸出 還有:conn.setUseCaches(false); POST方法不能緩存,要手動設(shè)置為false, 具體實現(xiàn)看代碼:

運行效果圖:

核心代碼

PostUtils.java

public class PostUtils {
    public static String LOGIN_URL = "http://172.16.2.54:8080/HttpTest/ServletForPost";
    public static String LoginByPost(String number,String passwd)
    {
        String msg = "";
        try{
            HttpURLConnection conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
            //設(shè)置請求方式,請求超時信息
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            //設(shè)置運行輸入,輸出:
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //Post方式不能緩存,需手動設(shè)置為false
            conn.setUseCaches(false);
            //我們請求的數(shù)據(jù):
            String data = "passwd="+ URLEncoder.encode(passwd, "UTF-8")+
                    "&number="+ URLEncoder.encode(number, "UTF-8");
            //這里可以寫一些請求頭的東東...
            //獲取輸出流
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.flush();
             if (conn.getResponseCode() == 200) {  
                    // 獲取響應(yīng)的輸入流對象  
                    InputStream is = conn.getInputStream();  
                    // 創(chuàng)建字節(jié)輸出流對象  
                    ByteArrayOutputStream message = new ByteArrayOutputStream();  
                    // 定義讀取的長度  
                    int len = 0;  
                    // 定義緩沖區(qū)  
                    byte buffer[] = new byte[1024];  
                    // 按照緩沖區(qū)的大小,循環(huán)讀取  
                    while ((len = is.read(buffer)) != -1) {  
                        // 根據(jù)讀取的長度寫入到os對象中  
                        message.write(buffer, 0, len);  
                    }  
                    // 釋放資源  
                    is.close();  
                    message.close();  
                    // 返回字符串  
                    msg = new String(message.toByteArray());  
                    return msg;
             }
        }catch(Exception e){e.printStackTrace();}
        return msg;
    }
}

PS:因為電腦沒裝MyEclipse,而且時間關(guān)系,就不另外寫demo了,用回之前的Eclipse的那個demo! 其實從直接看核心代碼就夠了~ 代碼下載:HttpURLConnection例子.zip


4.Cookie問題的處理

說這個之前,首先我們要理解兩個概念:Session和Cookie Cookie只是Session機制的一種常用形式,我們也可以使用其他方式來作為客戶端的一個唯一標識, 這個由服務(wù)器決定,唯一能夠證明一個客戶端標識就好!除了這種方式外,我們還可以使用URL重寫! 方法來實現(xiàn)!所以以后別傻傻的跟別人說:Session不就是Cookie!

下面通過一個例子來幫助大家理解這個Cookie: 小豬輸入賬號密碼后登陸下學(xué)校的教務(wù)系統(tǒng),然后訪問課表信息成功, 然后如果你用的是Chrome,按F12進入開發(fā)模式:來到Resources界面可以看到我們的Cookies:


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號