Android中HttpURLConnection与HttpClient的使用与封装

2019-12-10 18:50:58刘景俊
易采站长站为您分析Android中HttpURLConnection与HttpClient的使用以及封装方法,感兴趣的小伙伴们可以参考一下  

1.写在前面

    大部分andriod应用需要与服务器进行数据交互,HTTP、FTP、SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议。
    本文并不针对HTTP协议的具体内容,仅探讨android开发中使用HTTP协议访问网络的两种方式——HttpURLConnection和HttpClient
    因为需要访问网络,需在AndroidManifest.xml中添加如下权限

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

2.HttpURLConnection

2.1 GET方式

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
// 以下代码实现了以GET方式发起HTTP请求
// 连接网络是耗时操作,一般新建线程进行
 
private void connectWithHttpURLConnection() {
  new Thread( new Runnable() {
    @Override
    public void run() {
      HttpURLConnection connection = null;
      try {
        // 调用URL对象的openConnection方法获取HttpURLConnection的实例
        URL url = new URL("http://www.easck.com// 设置请求方式,GET或POST
        connection.setRequestMethod("GET");
        // 设置连接超时、读取超时的时间,单位为毫秒(ms)
        connection.setConnectTimeout(8000);
        connection.setReadTimeout(8000);
        // getInputStream方法获取服务器返回的输入流
        InputStream in = connection.getInputStream();
        // 使用BufferedReader对象读取返回的数据流
        // 按行读取,存储在StringBuider对象response中
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
          response.append(line);
        }
        //..........
        // 此处省略处理数据的代码
        // 若需要更新UI,需将数据传回主线程,具体可搜索android多线程编程
      } catch (Exception e){
        e.printStackTrace();
      } finally {
        if (connection != null){
          // 结束后,关闭连接
          connection.disconnect();
        }
      }
    }
  }).start();
}