学而实习之 不亦乐乎

Android:HttpURLConnection使用

2021-02-01 11:34:55

一、简介

由于 HttpClient 存在 API数量过多,扩展困难,在Android 6.0中被完全移除,官方建议使用 HttpURLConnection。当然 OkHttp 这个第三方的库也是很好用的,本文只介绍 HttpURLConnection 基本用法。

二、用法 

1.获取 HttpURLConnection 实例

URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();

2.设置 HTTP 请求的方法

HTTP/1.1协议中共定义了8种请求方法,最常用的有 GET 和 POST 两种。

connection.setRequestMethod("GET");

connection.setRequestMethod("POST");

3.设置头信息和连接参数

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty(HttpHeaderName.RESPONSE_HEADER_AUTH, reqToken);
connection.setRequestProperty(HttpHeaderName.RESPONSE_HEADER_TPARAM, reqTParam);

// 表示设置请求体的类型是文本类型
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));

4.获得输出流,向服务器输出数据

OutputStream outputStream = connection.getOutputStream();
outputStream.write(mydata, 0, mydata.length);
outputStream.close();

5.获得输入流,从服务器得到响应数据

int responseCode = connection.getResponseCode();
String headerdata = java.net.URLDecoder.decode(connection.getHeaderField("DATA"),"utf-8");
if (responseCode == 200) {
    InputStream in = connection.getInputStream();
    
    // 下面对获取到的输入流进行读取
    reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
    StringBuilder response = new StringBuilder();
    String line;

    while ((line = reader.readLine()) != null) {
        response.append(line);
    }

    respStr = response.toString();
    respJson = java.net.URLDecoder.decode(connection.getHeaderField("ZHXK_RESP_DATA"),"utf-8");
}

三、实例

public class HttpHelper {

    public static String doPost(String servlet,String regJsonData) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String respJson = null;
        try {
            URL url = new URL(servlet);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");            
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");// 设置文件类型
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("Authorization", "Authorization");// 设置Authorization信息
            connection.setRequestProperty("Param", "Param");// 设置参数信息

            // 往服务器里面发送数据
            if (regJsonData != null && !TextUtils.isEmpty(regJsonData)) {
                byte[] writebytes = regJsonData.getBytes();// 设置文件长度
                connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = connection.getOutputStream();
                outwritestream.write(regJsonData.getBytes());
                outwritestream.flush();
                outwritestream.close();
            }

            InputStream in = connection.getInputStream();
            // 下面对获取到的输入流进行读取
            reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            
            respJson = java.net.URLDecoder.decode(connection.getHeaderField("DATA"),"utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
            return respJson;
        }
    }
}