Http interface call in Android

The Http interface access we want to talk about today is implemented using the HttpURLConnection object. Someone will ask, why do you say this? We all use okhttp or Retrofit. If it's not easy to use, it's also the secondary packaging written by others. Why does it come out with such primitive things? Is this what bloggers use. This I don't need this either. However, in line with the principle of the general meeting, I would like to summarize here.

1. Get HttpURLConnection object

URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

2. API related to httpurlconnection

  • setRequestMethod: sets the request type. Get means get request and post means post request.
  • setConnectTimeout: sets the timeout of the connection.
  • setReadTimeout: sets the timeout for reading.
  • setRequestProperty: sets the property information of the request packet header.
  • setDoOutput: set whether to allow sending data. If the getOutputStream method is used, setDoOuput must be set to true. Because POST mode will definitely send data, this method must be set when POST is called.
  • getOutputStream: get HTTP output stream. Call this function to return an OutputStream object, and then call the write and flush methods of the object in turn to write the data to be sent.
  • connect: establish an HTTP connection.
  • setDoInput: set whether to allow receiving data. If the getInputStream method is used, setDoInput must be set to true (in fact, it does not need to be set manually, because the default is true).
  • getInputStream: get HTTP input stream. Call this function to return an InputStream object, and then call the read method of the object to read out the received data.
  • getResponseCode: get the HTTP return code.
  • getHeaderField: get the specified attribute value of the response packet header.
  • getHeaderFields: get the list of all properties of the response packet header.
  • Disconnect: disconnect the HTTP connection.

3.HttpURLConnection request example -- simple get and post requests

public class HttpRequestUtil {
    private static final String TAG = "HttpRequestUtil";

    // Set header information of http connection
    private static void setConnHeader(HttpURLConnection conn, String method, HttpReqData req_data)
            throws ProtocolException {
        // Set the request method. There are two common methods: GET and POST
        conn.setRequestMethod(method);
        // Set connection timeout
        conn.setConnectTimeout(5000);
        // Set read-write timeout
        conn.setReadTimeout(10000);
        // Format data
        conn.setRequestProperty("Accept", "*/*");
        // IE use
//        conn.setRequestProperty("Accept-Language", "zh-CN");
//        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C)");
        // firefox usage
        // Set text language
        conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        // Set up user agent
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
        // Set encoding format
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        if (!req_data.content_type.equals("")) {
            // Set content type
            conn.setRequestProperty("Content-Type", req_data.content_type);
        }
        if (!req_data.x_requested_with.equals("")) {
            // Determine whether the request is from an Ajax request or a traditional request
            conn.setRequestProperty("X-Requested-With", req_data.x_requested_with);
        }
        if (!req_data.referer.equals("")) {
            // Set jump source
            conn.setRequestProperty("Referer", req_data.referer);
        }
        if (!req_data.cookie.equals("")) {
            // Set up a secret note
            conn.setRequestProperty("Cookie", req_data.cookie);
            Log.d(TAG, "setConnHeader cookie=" + req_data.cookie);
        }
    }

    private static String getRespCookie(HttpURLConnection conn, HttpReqData req_data) {
        String cookie = "";
        Map<String, List<String>> headerFields = conn.getHeaderFields();
        if (headerFields != null) {
            List<String> cookies = headerFields.get("Set-Cookie");
            if (cookies != null) {
                for (String cookie_item : cookies) {
                    cookie = cookie + cookie_item + "; ";
                }
            } else {
                cookie = req_data.cookie;
            }
        } else {
            cookie = req_data.cookie;
        }
        Log.d(TAG, "cookie=" + cookie);
        return cookie;
    }

    // get text data
    public static HttpRespData getData(HttpReqData req_data) {
        HttpRespData resp_data = new HttpRespData();
        try {
            URL url = new URL(req_data.url);
            // Creates an HTTP connection with the specified network address
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            setConnHeader(conn, "GET", req_data);
            conn.connect(); // Start connection
            // Decompress the data in the input stream to get the original response string
            resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
                    conn.getHeaderField("Content-Encoding"), req_data.charset);
            resp_data.cookie = conn.getHeaderField("Set-Cookie");
            conn.disconnect(); // Disconnect
        } catch (Exception e) {
            e.printStackTrace();
            resp_data.err_msg = e.getMessage();
        }
        return resp_data;
    }

    // get picture data
    public static HttpRespData getImage(HttpReqData req_data) {
        HttpRespData resp_data = new HttpRespData();
        try {
            URL url = new URL(req_data.url);
            // Creates an HTTP connection with the specified network address
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            setConnHeader(conn, "GET", req_data);
            conn.connect(); // Start connection
            // Get input stream from HTTP connection
            InputStream is = conn.getInputStream();
            // Decode the data in the input stream to get the bitmap object
            resp_data.bitmap = BitmapFactory.decodeStream(is);
            resp_data.cookie = conn.getHeaderField("Set-Cookie");
            conn.disconnect(); // Disconnect
        } catch (Exception e) {
            e.printStackTrace();
            resp_data.err_msg = e.getMessage();
        }
        return resp_data;
    }

    // The content of the post is placed in the url
    public static HttpRespData postUrl(HttpReqData req_data) {
        HttpRespData resp_data = new HttpRespData();
        String s_url = req_data.url;
        if (req_data.params != null && !req_data.params.toString().isEmpty()) {
            s_url += "?" + req_data.params.toString();
        }
        Log.d(TAG, "s_url=" + s_url);
        try {
            URL url = new URL(s_url);
            // Creates an HTTP connection with the specified network address
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            setConnHeader(conn, "POST", req_data);
            conn.setDoOutput(true);
            conn.connect(); // Start connection
            resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
                    conn.getHeaderField("Content-Encoding"), req_data.charset);
            resp_data.cookie = conn.getHeaderField("Set-Cookie");
            conn.disconnect(); // Disconnect
        } catch (Exception e) {
            e.printStackTrace();
            resp_data.err_msg = e.getMessage();
        }
        return resp_data;
    }

    // The contents of the post are placed in the output stream
    public static HttpRespData postData(HttpReqData req_data) {
        req_data.content_type = "application/x-www-form-urlencoded";
        HttpRespData resp_data = new HttpRespData();
        String s_url = req_data.url;
        Log.d(TAG, "s_url=" + s_url + ", params=" + req_data.params.toString());
        try {
            URL url = new URL(s_url);
            // Creates an HTTP connection with the specified network address
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            setConnHeader(conn, "POST", req_data);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect(); // Start connection
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(req_data.params.toString());
            out.flush();
            // Decompress the data in the input stream to get the original response string
            resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
                    conn.getHeaderField("Content-Encoding"), req_data.charset);
            resp_data.cookie = getRespCookie(conn, req_data);
            conn.disconnect(); // Disconnect
        } catch (Exception e) {
            e.printStackTrace();
            resp_data.err_msg = e.getMessage();
        }
        return resp_data;
    }

    // Content segmented transmission of post
    public static HttpRespData postMultiData(HttpReqData req_data, Map<String, String> map) {
        HttpRespData resp_data = new HttpRespData();
        String s_url = req_data.url;
        Log.d(TAG, "s_url=" + s_url);
        String end = "\r\n";
        String hyphens = "--";
        try {
            URL url = new URL(s_url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            setConnHeader(conn, "POST", req_data);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + req_data.boundary);
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            StringBuilder buffer = new StringBuilder();
            Log.d(TAG, "map.size()=" + map.size());
            for (String str : map.keySet()) {
                buffer.append(hyphens + req_data.boundary + end);
                buffer.append("Content-Disposition: form-data; name=\"");
                buffer.append(str);
                buffer.append("\"" + end + end);
                buffer.append(map.get(str));
                buffer.append(end);
                Log.d(TAG, "key=" + str + ", value=" + map.get(str));
            }
            if (map.size() > 0) {
                buffer.append(hyphens + req_data.boundary + end);
                byte[] param_data = buffer.toString().getBytes(req_data.charset);
                OutputStream out = conn.getOutputStream();
                out.write(param_data);
                out.flush();
            }

            conn.connect(); // Start connection
            // Decompress the data in the input stream to get the original response string
            resp_data.content = StreamTool.getUnzipStream(conn.getInputStream(),
                    conn.getHeaderField("Content-Encoding"), req_data.charset);
            resp_data.cookie = conn.getHeaderField("Set-Cookie");
            conn.disconnect(); // Disconnect
        } catch (Exception e) {
            e.printStackTrace();
            resp_data.err_msg = e.getMessage();
        }
        return resp_data;
    }

}

4. Precautions

In addition, Android 9 can only access the security address starting with https by default, and cannot directly access the network address starting with HTTP. If the application still wants to access the normal address starting with HTTP, it has to modify androidmanifest XML, add the following attributes to the application node to indicate that the HTTP plaintext address will continue to be used:

android:usesCleartextTraffic="true"

 

Added by ejaboneta on Tue, 08 Mar 2022 08:19:17 +0200