android HttpURLConnection

Keywords: Mobile Android JSON network SDK

After android 6.0 (api 23) sdk, HttpClient is no longer available, so the native network request for android is HttpURLConnection.

introduce

Comparison between HttpClient and HttpURLConnection

1. HttpClient is an open source framework of apache. It encapsulates the request header, parameters, content body and response waiting for accessing http. It is more convenient to use. HttpURLConnection is a standard class of java. It is not encapsulated. It is too primitive and inconvenient to use, such as customization of re-access and some advanced functions.

2. From the aspect of stability, HttpClient is very stable, powerful, with few Bug s and easy to control details. The previous version of HttpURLConnection has been compatible, but it has been repaired in subsequent versions.

Why abolish HttpClient?

1. HttpUrlConnection is the standard implementation of Android SDK, while HttpClient is the open source implementation of apache.

2. HttpUrlConnection directly supports GZIP compression, and HttpClient also supports it, but it has to write its own code for processing.

3. HttpUrlConnection Direct Support System Level Connection Pool, that is, open connections will not be closed directly, all programs can be shared in a period of time, HttpClient of course can do it, but after all, it is not as good as the official direct system bottom support.

4. HttpUrlConnection directly processes the caching strategy in the system to accelerate the speed of repeated requests.

GET Request Implementation

private void requestGet(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/getUsers?";
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String requestUrl = baseUrl + tempParams.toString();
            // Create a new URL object
            URL url = new URL(requestUrl);
            // Open an HttpURLConnection connection
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // Setting connection host timeout
            urlConn.setConnectTimeout(5 * 1000);
            //Set timeout for reading data from host
            urlConn.setReadTimeout(5 * 1000);
            // Setting whether to use caching by default is true
            urlConn.setUseCaches(true);
            // Set to Post Request
            urlConn.setRequestMethod("GET");
            //urlConn Sets Request Header Information
            //Set the media type information in the request.
            urlConn.setRequestProperty("Content-Type", "application/json");
            //Setting the connection type between client and service
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // Start connecting
            urlConn.connect();
            // Determine whether the request was successful
            if (urlConn.getResponseCode() == 200) {
                // Get the returned data
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "Get The method requests success. result--->" + result);
            } else {
                Log.e(TAG, "Get Mode request failed");
            }
            // Close connection
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

POST Request Implementation

private void requestPost(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/getUsers";
            //Synthesis parameters
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key,  URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String params =tempParams.toString();
            // The parameters of the request are converted to byte arrays
            byte[] postData = params.getBytes();
            // Create a new URL object
            URL url = new URL(baseUrl);
            // Open an HttpURLConnection connection
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // Set connection timeout
            urlConn.setConnectTimeout(5 * 1000);
            //Set timeout for reading data from host
            urlConn.setReadTimeout(5 * 1000);
            // Post requests must be set to allow default false output
            urlConn.setDoOutput(true);
            //Setting the request to allow input by default is true
            urlConn.setDoInput(true);
            // Post requests cannot use caching
            urlConn.setUseCaches(false);
            // Set to Post Request
            urlConn.setRequestMethod("POST");
            //Set whether this connection automatically handles redirection
            urlConn.setInstanceFollowRedirects(true);
            // Configuration Request Content-Type
            urlConn.setRequestProperty("Content-Type", "application/json");
            // Start connecting
            urlConn.connect();
            // Send request parameters
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // Determine whether the request was successful
            if (urlConn.getResponseCode() == 200) {
                // Get the returned data
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "Post The method requests success. result--->" + result);
            } else {
                Log.e(TAG, "Post Mode request failed");
            }
            // Close connection
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

Processing network flows: Converting input streams to strings

private void requestPost(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/getUsers";
            //Synthesis parameters
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key,  URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String params =tempParams.toString();
            // The parameters of the request are converted to byte arrays
            byte[] postData = params.getBytes();
            // Create a new URL object
            URL url = new URL(baseUrl);
            // Open an HttpURLConnection connection
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // Set connection timeout
            urlConn.setConnectTimeout(5 * 1000);
            //Set timeout for reading data from host
            urlConn.setReadTimeout(5 * 1000);
            // Post requests must be set to allow default false output
            urlConn.setDoOutput(true);
            //Setting the request to allow input by default is true
            urlConn.setDoInput(true);
            // Post requests cannot use caching
            urlConn.setUseCaches(false);
            // Set to Post Request
            urlConn.setRequestMethod("POST");
            //Set whether this connection automatically handles redirection
            urlConn.setInstanceFollowRedirects(true);
            // Configuration Request Content-Type
            urlConn.setRequestProperty("Content-Type", "application/json");
            // Start connecting
            urlConn.connect();
            // Send request parameters
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // Determine whether the request was successful
            if (urlConn.getResponseCode() == 200) {
                // Get the returned data
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "Post The method requests success. result--->" + result);
            } else {
                Log.e(TAG, "Post Mode request failed");
            }
            // Close connection
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

File download

private void downloadFile(String fileUrl){
        try {
            // Create a new URL object
            URL url = new URL(fileUrl);
            // Open an HttpURLConnection connection
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // Setting connection host timeout
            urlConn.setConnectTimeout(5 * 1000);
            //Set timeout for reading data from host
            urlConn.setReadTimeout(5 * 1000);
            // Setting whether to use caching by default is true
            urlConn.setUseCaches(true);
            // Set to Post Request
            urlConn.setRequestMethod("GET");
            //urlConn Sets Request Header Information
            //Set the media type information in the request.
            urlConn.setRequestProperty("Content-Type", "application/json");
            //Setting the connection type between client and service
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // Start connecting
            urlConn.connect();
            // Determine whether the request was successful
            if (urlConn.getResponseCode() == 200) {
                String filePath="";
                File  descFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(descFile);;
                byte[] buffer = new byte[1024];
                int len;
                InputStream inputStream = urlConn.getInputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    // Write to local
                    fos.write(buffer, 0, len);
                }
            } else {
                Log.e(TAG, "File download failed");
            }
            // Close connection
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

File upload

private void upLoadFile(String filePath, HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/uploadFile";
            File file = new File(filePath);
            //New url object
            URL url = new URL(baseUrl);
            //Send requests to network addresses through the HttpURLConnection object
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            //Set the connection to allow reading
            urlConn.setDoOutput(true);
            //Set the connection to allow writing
            urlConn.setDoInput(true);
            //Settings do not apply to caching
            urlConn.setUseCaches(false);
            //Set connection timeout
            urlConn.setConnectTimeout(5 * 1000);   //Set connection timeout
            //Setting the read timeout time
            urlConn.setReadTimeout(5 * 1000);   //Read timeout
            //Setting the connection method post
            urlConn.setRequestMethod("POST");
            //Setting up to maintain long connections
            urlConn.setRequestProperty("connection", "Keep-Alive");
            //Setting the file character set
            urlConn.setRequestProperty("Accept-Charset", "UTF-8");
            //set file type
            urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
            String name = file.getName();
            DataOutputStream requestStream = new DataOutputStream(urlConn.getOutputStream());
            requestStream.writeBytes("--" + "*****" + "\r\n");
            //Send file parameter information
            StringBuilder tempParams = new StringBuilder();
            tempParams.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\"; ");
            int pos = 0;
            int size=paramsMap.size();
            for (String key : paramsMap.keySet()) {
                tempParams.append( String.format("%s=\"%s\"", key, paramsMap.get(key), "utf-8"));
                if (pos < size-1) {
                    tempParams.append("; ");
                }
                pos++;
            }
            tempParams.append("\r\n");
            tempParams.append("Content-Type: application/octet-stream\r\n");
            tempParams.append("\r\n");
            String params = tempParams.toString();
            requestStream.writeBytes(params);
            //Send file data
            FileInputStream fileInput = new FileInputStream(file);
            int bytesRead;
            byte[] buffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            while ((bytesRead = in.read(buffer)) != -1) {
                requestStream.write(buffer, 0, bytesRead);
            }
            requestStream.writeBytes("\r\n");
            requestStream.flush();
            requestStream.writeBytes("--" + "*****" + "--" + "\r\n");
            requestStream.flush();
            fileInput.close();
            int statusCode = urlConn.getResponseCode();
            if (statusCode == 200) {
                // Get the returned data
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "The upload was successful. result--->" + result);
            } else {
                Log.e(TAG, "Upload failure");
            }
        } catch (IOException e) {
            Log.e(TAG, e.toString());
        }
    }

Jurisdiction

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

 

Finally, welcome to visit my personal website: 1024s​​​​​​​

Posted by EATON106 on Fri, 01 Feb 2019 03:51:16 -0800