Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

Android HTTP 請求方式:HttpURLConnection 詳解

編輯:Android 技術基礎

本節引言

前面兩節我們學習的都是一些概念性的東西,比如 HTTP 協議以及協議頭的相關知識,而本節就要開始堆碼了。本節學習的是 Android 為我們提供的 HTTP 請求方式之一:HttpURLConnection。除了這種,還有一種 HttpClient,後者我們會在下一節講。不過前者一旦請求複雜起來,使用起來就非常麻煩,而後者我們用 Java 抓包時也經常會用到,它是 Apache 的,畢竟不是谷歌親兒子——而在 4.4 版本,HttpURLConnection 已被替換成 OkHttp 了。與時俱進,決定講完 HttpClient 後也來會一會這個 OkHttp。對了,一般實際開發並不會直接用 HttpURLConnection 和 HttpClient,而是使用別人封裝好的第三方網絡請求框架,諸如 Volley、android-async-http、loopj 等,因為網絡操作涉及異步與多線程,自己動手撸很麻煩,所以實際開發還是直接用第三方。當然學習一下也無妨,畢竟第三方也是在這些基礎上撸起來的,架構逼格高,還做了各種優化。話不多說,開始本節內容。


一、HttpURLConnection 的介紹

答:一種多用途、輕量級的 HTTP 客戶端,使用它來進行 HTTP 操作可以適用於大多數應用程序。雖然 HttpURLConnection 的 API 比較簡單,但這也讓我們更容易使用和擴展它。它繼承自 URLConnection,是一個抽象類,無法直接實例化對象,通過調用 openConnection() 方法獲得對象實例,默認是帶 gzip 壓縮的。


二、HttpURLConnection 的使用步驟

使用 HttpURLConnection 的步驟如下:

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

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


三、HttpURLConnection 使用示例

這裡我們主要針對 GET 和 POST 請求寫兩個不同的使用示例。我們可以通過 conn.getInputStream() 獲取到的是一個流,所以我們需要寫一個類把流轉化為字節數組。工具類如下:

StreamTool.java:

 /** * Created by Jay on 2015/9/7 0007. */ public class StreamTool { //從流中讀取數據 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 發送 GET 請求代碼示例

運行效果圖:

核心部分代碼:

布局:activity_main.xml

 <LinearLayout xmlns:android="https://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> 

獲取數據類:GetData.java:

 /** * Created by Jay on 2015/9/7 0007. */ public class GetData { // 定義一個獲取網絡圖片數據的方法: public static byte[] getImage(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 設置連接超時為5秒 conn.setConnectTimeout(5000); // 設置請求類型為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; } // 獲取網頁的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 = "https://ww2.sinaimg.cn/large/7a8aed7bgw1evshgr5z3oj20hs0qo0vq.jpg"; private final static String HTML_URL = "https://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, "網頁加載完畢", 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 // 重寫上下文菜單的創建方法 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); } // 上下文菜單被點擊是觸發該方法 @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; } } 

最後別忘了加上聯網權限:

 <uses-permission android:name="android.permission.INTERNET" /> 

注意事項:

用 handler 的原因就不用講了吧。另外,我們加載 html 代碼時用的是 WebView 的 loadDataWithBaseURL 而非 loadData,如果用 loadData 又要去糾結中文亂碼問題,所以用 loadDataWithBaseURL 就可以省卻很多麻煩。另外有些頁面可能需要我們提交一些參數,比如賬號密碼,我們只需把對應參數拼接到 url 尾部即可,比如 https://192.168.191.1:8080/ComentServer/LoginServlet?passwd=123&name=Jack,然後服務端用 getParameter("passwd") 就能獲得相應參數了。我們請求時這些東西都會看得清清楚楚,所以說 GET 方式並不安全。另外還要注意,Android 從 4.0 開始就不允許在非 UI 線程中進行 UI 操作。


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

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

運行效果圖:

核心代碼:

PostUtils.java

 public class PostUtils { public static String LOGIN_URL = "https://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(); //設置請求方式,請求超時信息 conn.setRequestMethod("POST"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); //設置運行輸入,輸出: conn.setDoOutput(true); conn.setDoInput(true); //Post方式不能緩存,需手動設置為false conn.setUseCaches(false); //我們請求的數據: 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) { // 獲取響應的輸入流對象 InputStream is = conn.getInputStream(); // 創建字節輸出流對象 ByteArrayOutputStream message = new ByteArrayOutputStream(); // 定義讀取的長度 int len = 0; // 定義緩沖區 byte buffer[] = new byte[1024]; // 按照緩沖區的大小,循環讀取 while ((len = is.read(buffer)) != -1) { // 根據讀取的長度寫入到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:因為沒裝相應的 IDE,而且時間關係,就不另外寫 demo 了,直接看核心代碼就夠了。代碼下載:HttpURLConnection 例子.zip。


四、Cookie 問題的處理

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

下面通過一個例子幫助大家理解 Cookie:小豬輸入賬號密碼登錄學校的教務系統,然後訪問課表信息成功。如果你用的是 Chrome,按 F12 進入開發模式,來到 Resources 界面可以看到我們的 Cookies:

點擊後可以看到裡面保存的內容:由名稱、值、cookie 所在的域(domain)、cookie 所在的目錄(path,Asp.net 默認為 / 即根目錄)、過期時間、Cookie 大小組成。

我們可以看到請求頭中有一個 Cookie 的字段:

現在把 Cookie 清掉(或者等幾分鐘),然後再訪問下述鏈接:

這時候,頁面竟然自動跳回登錄頁面了。當然,一些其他網站可能會彈出一個對話框說「登錄超時」之類的東西。

小結一下 HTTP 請求登錄的簡單流程:一般是登錄時,服務器通過 Set-Cookie 響應頭返回一個 Cookie,瀏覽器默認保存這個 Cookie,後續訪問相關頁面時會帶上這個 Cookie,通過 Cookie 請求頭完成訪問;如果沒有 Cookie 或 Cookie 過期,就提示用戶沒登錄、登錄超時、需要登錄之類的信息。

而我們使用 HttpClient 和 HttpURLConnection,其實也就是模擬這一個流程:登錄後拿到 cookie,拿著它去發送請求。關鍵代碼如下:獲得 Cookie:conn.getHeaderField("Set-Cookie"); 請求時帶上 Cookie:conn.setRequestProperty("Cookie",cookie);

另外,除了這種設置請求頭的方式外,還可以用另一種折衷的方法:URL 重寫,就是在原先請求鏈接的基礎上,加上一個 …&sessionid=xxxxx 這樣的參數,然後由服務器來解析判斷。GET 可以這麼寫,而 POST 寫法如下:

這裡我們用的是 JSON 字符串的形式,接到請求時服務端取出 session 裡的內容,然後做下查詢即可。


五、使用 HttpURLConnection 發送 PUT 請求

PUT 請求對於很多朋友來說可能有點陌生,畢竟我們平時接觸比較多的都是 GET 和 POST。一開始也不了解,不過後來才發現 PUT 和 POST 其實差不多,而且我們只需在 POST 的基礎上改點東西就能使用了。而 HttpClient 也給我們提供了一個 HttpPut 的 API。下面貼一下項目中寫的請求代碼:

 public static String LoginByPut(Context mContext, String mobile, String password, int from, String devid,String version_name, int remember_me) { String resp = ""; try { HttpURLConnection conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setRequestMethod("PUT"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); String data = "mobile=" + mobile + "&password=" + password + "&from=" + from + "&devid=" + "devid" + "&version_name=" + "version_name" + "&remember_me=" + remember_me; ; // 獲取輸出流: OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); // 獲取相應流對象: InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) response.append(line); SPUtils.put(mContext, "session", conn.getHeaderField("Set-Cookie")); // 資源釋放: in.close(); // 返回字符串 Log.e("HEHE", response.toString()); return response.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } 

本節小結

本節關於 HttpURLConnection 的使用介紹就到這裡。另外,HTTP 這一小節大部分來自於以前寫的一個小合集《Android 之 Http 通信》,如果看過這個系列的可以跳過本節,大部分內容都一樣。本節就說這麼多,謝謝。

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