Android中HttpURLConnection与HttpClient的使用与封装

2019-12-10 18:50:58刘景俊

3.3 android 6.0移除HttpClient

android 6.0(API 23)版本的SDK已将Apache HttpClient相关类移除,解决办法自行GOOGLE,推荐使用HTTPURLConnection。
若还需使用该类,点击查看解决办法。
4.HttpURLConnection实战
如果你使用过JQuery(一个javasript库),你一定对JQuery的网路编程印象深刻,比如一个HTTP请求只需以下几行代码。

// JQuery的post方法
$.post("http://www.easck.com//...请求成功的代码
  }).fail(function(){
    //...请求失败的代码
  }).always(function(){
    //...总会执行的代码
  })

    我们当然不希望每次网络请求都写下2.1中那么繁琐的代码,那么android的HTTP请求能否像JQuery那么简单呢?当然可以!下面的代码实现了HttpURLConnection的HTTP请求方法封装:

4.1 定义接口HttpCallbackListener,为了实现回调

// 定义HttpCallbackListener接口
// 包含两个方法,成功和失败的回调函数定义
public interface HttpCallbackListener {
  void onFinish(String response);
  void onError(Exception e);
}

4.2 创建HttpTool类,抽象请求方法(GET)

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
/* 创建一个新的类 HttpTool,将公共的操作抽象出来
 * 为了避免调用sendRequest方法时需实例化,设置为静态方法
 * 传入HttpCallbackListener对象为了方法回调
 * 因为网络请求比较耗时,一般在子线程中进行,
 * 为了获得服务器返回的数据,需要使用java的回调机制 */
 
public class HttpTool {
  public static void sendRequest(final String address, 
      final HttpCallbackListener listener) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        HttpURLConnection connection = null;
 
        try {
          URL url = new URL(address);
          connection = (HttpURLConnection) url.openConnection();
          connection.setRequestMethod("GET");
          connection.setConnectTimeout(8000);
          connection.setReadTimeout(8000);
          InputStream in = connection.getInputStream();
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          StringBuilder response = new StringBuilder();   String line;
          while ((line = reader.readLine()) != null) {
            response.append(line);
          }
          if (listener != null) {
            // 回调方法 onFinish()
            listener.onFinish(response.toString());
          }
        } catch (Exception e) {
          if (listener != null) {
            // 回调方法 onError()
            listener.onError(e);
          }
        } finally {
          if (connection != null) {
            connection.disconnect();
          }
        }
      }
    }).start();
  }
}