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

Android 網絡請求的兩種方式:HttpURLConnection 與 HttpClient

編輯:關於 Android 程式設計

在 Android 應用開發中,我們往往需要與服務器交互,獲取或上傳數據,這就要用到網絡請求。一般情況下,我們使用 HTTP 協議來發送和接收數據,而 HTTP 通信又有兩種常見方式:HttpURLConnection 和 HttpClient。

示例代碼:https://git.oschina.net/ysx_xx/HttpText/tree/master

下面簡單介紹這兩種方式的使用。

首先,要進行網絡請求,我們需要給應用添加網絡權限,有兩種添加方式:

1. 打開 AndroidManifest.xml 文件,選擇 permission,點擊 Add:

選擇最後一個 UsesPermission:

然後在右邊 Name 選項中找到 android.permission.INTERNET,保存:

接著再選擇 AndroidManifest.xml 選項,就能看到:

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

2. 第二種方法就是直接在 AndroidManifest 中加上面那句話,前提是你要熟悉怎麼寫。


好了,下面來講講那兩種請求方式的用法。

1. HttpURLConnection:

先 new 一個 URL 對象並傳入網絡地址,再調用 openConnection() 方法取得 HttpURLConnection 實例,然後設置 HTTP 請求方法(GET/POST),接著設置連接超時、讀取超時、消息頭等(可根據實際情況編寫),之後用 getInputStream() 取得服務器返回的輸入流並讀取內容,最後調用 disconnect() 關閉連接。

代碼:

new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL("https://www.baidu.com/"); // 調用 URL 的 openConnection(),得到 HttpURLConnection 實例 connection = (HttpURLConnection) url.openConnection(); // 設置 HTTP 請求方法為 GET,GET 一般用於從服務器獲取數據,POST 用於提交數據給服務器 connection.setRequestMethod("GET"); // 設置連接超時的毫秒數 connection.setConnectTimeout(8000); // 設置讀取超時的毫秒數 connection.setReadTimeout(8000); // 獲取服務器返回的輸入流 InputStream in = connection.getInputStream(); // 讀取獲取到的輸入流 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String response = "", line; while ((line = reader.readLine()) != null) { response += line; } //獲取成功,發送成功信息 Message message = new Message(); message.what = SUCCESS; message.obj = response; mHandler.sendMessage(message); } catch (Exception e) { //發送失敗信息 Message message = new Message(); message.what = FAILE; message.obj = "請求失敗"; mHandler.sendMessage(message); e.printStackTrace(); } finally { if (connection != null) { //關閉連接 connection.disconnect(); } } } }).start();

運行效果如下:

以上是 GET 方式的介紹。如果要向服務器提交數據呢?我們可以把請求方式改為 POST 並提交參數。例如:

connection.setRequestMethod("POST"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes("username=小熊&password=123456");

2. 下面看看 HttpClient 的用法:

HttpClient 是一個接口。我們要先創建一個 DefaultHttpClient 的實例,再創建一個 HttpGet 對象並傳入網絡地址,然後調用 HttpClient 的 execute() 發送 GET 請求,最後通過 HttpResponse 的 getStatusLine().getStatusCode() 取得服務器返回的狀態碼,若為 200 則說明成功。

代碼:

new Thread(new Runnable() { @Override public void run() { try { //因為 HttpClient 是一個接口,所以用 DefaultHttpClient() 創建一個實例 HttpClient httpClient = new DefaultHttpClient(); //創建 HttpGet 對象並傳入網絡地址,調用 execute 發送 GET 請求 HttpGet httpGet = new HttpGet("https://www.baidu.com"); HttpResponse httpResponse = httpClient.execute(httpGet); //先取出服務器返回的狀態碼,如果是 200 則說明請求響應成功 if(httpResponse.getStatusLine().getStatusCode() == 200){ //請求響應成功,調用 getEntity() 取得 HttpEntity 實例並轉換成字符串 HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity, "utf-8"); //獲取成功,發送成功信息 Message message = new Message(); message.what = SUCCESS; message.obj = response; mHandler.sendMessage(message); } } catch (Exception e) { //發送失敗信息 Message message = new Message(); message.what = FAILE; message.obj = "請求失敗"; mHandler.sendMessage(message); e.printStackTrace(); } } }).start();

運行效果與 HttpURLConnection 一樣,這裡就不再重複貼圖了。下面是 HttpClient 的 POST 方式關鍵代碼:

HttpPost httpPost = new HttpPost("https://www.baidu.com"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "小熊")); params.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8"); httpPost.setEntity(entity); httpClient.execute(httpPost);

完整代碼:

HttpURLConnectionText.java:

public class HttpURLConnectionText extends Activity implements OnClickListener { private final static int SUCCESS = 1; private final static int FAILE = 0; private TextView result; private Button send; private LoadingDialog loadingDialog; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); } private void initData() { mContext = this; result = (TextView) findViewById(R.id.result); send = (Button) findViewById(R.id.send); send.setOnClickListener(this); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { String response; if(loadingDialog != null && loadingDialog.isShowing()){ loadingDialog.dismiss(); } switch (msg.what) { case SUCCESS: response = msg.obj.toString(); result.setText(response); break; case FAILE: response = msg.obj.toString(); result.setText(response); break; } }; }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.send: loadingDialog = new LoadingDialog(mContext); loadingDialog.setCancel(false); loadingDialog.show(); startSend(); break; } } private void startSend() { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL("https://www.baidu.com/"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String response = "", line; while ((line = reader.readLine()) != null) { response += line; } Message message = new Message(); message.what = SUCCESS; message.obj = response; mHandler.sendMessage(message); } catch (Exception e) { Message message = new Message(); message.what = FAILE; message.obj = "請求失敗"; mHandler.sendMessage(message); e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }).start(); } }

HttpClientText.java:

public class HttpClientText extends Activity implements OnClickListener { private final static int SUCCESS = 1; private final static int FAILE = 0; private TextView result; private Button send; private LoadingDialog loadingDialog; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); } private void initData() { mContext = this; result = (TextView) findViewById(R.id.result); send = (Button) findViewById(R.id.send); send.setOnClickListener(this); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { String response; if(loadingDialog != null && loadingDialog.isShowing()){ loadingDialog.dismiss(); } switch (msg.what) { case SUCCESS: response = msg.obj.toString(); result.setText(response); break; case FAILE: response = msg.obj.toString(); result.setText(response); break; } }; }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.send: loadingDialog = new LoadingDialog(mContext); loadingDialog.setCancel(false); loadingDialog.show(); startSend(); break; } } private void startSend() { new Thread(new Runnable() { @Override public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("https://www.baidu.com"); HttpResponse httpResponse = httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200){ HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity, "utf-8"); Message message = new Message(); message.what = SUCCESS; message.obj = response; mHandler.sendMessage(message); } } catch (Exception e) { Message message = new Message(); message.what = FAILE; message.obj = "請求失敗"; mHandler.sendMessage(message); e.printStackTrace(); } } }).start(); } }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved