URLConnection is an abstract class with two direct subclasses: HttpURLConnection and JarURLConnection. Another important class is urls, which typically generate an instance of a URL pointing to a specific address by passing a String argument to the constructor. Each HttpURLConnection instance can be used to generate a single request, but other instances can transparently share the underlying network that connects to the HTTP server. Calling the close() method on an InputStream or OutputStream of an HttpURLConnection after the request frees the network resources associated with this instance, but has no effect on the shared persistent connection. If the persistent connection is idle when disconnect() is called, the underlying socket may be closed.

  • Request, makes a Post request and carries parameters to the server, which returns Json data

  • Code implementation

import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; /** * Created by yuandl on 2016-10-18. */ public class URLConnectionTest {public static void The main (String [] args) {String url = "http://10.58.178.72/intco/mobi/member/login"; HashMap params = new HashMap<>(); params.put("username", "13468857714"); params.put("pwd", MD5.md5("123456").toLowerCase()); requestPost(url, params); } /** * request ** @param paramsMap */ private static void requestPost(String httpUrl, HashMap paramsMap) { try { String baseUrl = httpUrl; 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(); System.out.println(" httpUrl-- >" + params); System.out.println("Post request params-- >" + params); byte[] postData = params.getBytes(); URL url = new URL(baseUrl); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(5 * 1000); urlConn.setReadTimeout(5 * 1000); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod("POST"); urlConn.setInstanceFollowRedirects(true); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.connect(); DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); dos.write(postData); dos.flush(); dos.close(); if (urlConn.getResponseCode() == 200) { String result = streamToString(urlConn.getInputStream()); System.out.println("Post request succeeded, result-- >" + result); } else {system.out.println ("Post request failed "); } urlConn.disconnect(); } catch (Exception e) { e.printStackTrace(); Public static String streamToString(InputStream is) {try {public static String streamToString(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) ! = -1) { baos.write(buffer, 0, len); } baos.close(); is.close(); byte[] byteArray = baos.toByteArray(); return new String(byteArray); } catch (Exception e) { e.printStackTrace(); return null; }}}Copy the code
Post requests address httpUrl -- - > the PWD = e10adc3949ba59abbe56e057f20f883e & username = 13468857714 Post way request parameter params - > the PWD = e10adc3949ba59abbe56e057f20f883e & username = 13468857714 Post request is successful, The result - > {" status ": 1," data ": {" mId" : "426 e743224db4ecb8313e069982a7496", "mName" : "* east bright", "PWD" : "f241426298243cb7f6f97da58749 ffb386c1457d","sex":"1","mobile":"13468857714","authentication":"0","personal":"0","isMain":"1","parentId":"0","newOrold ":" 1 ", "imgurl" : "http://10.58.178.72/intco/upload/img/member/portrait/2016/10/9331f754fbb742d99f6e61dcee0fe61d.jpg", "stat e":"1","rongcloud_token":"1XHoYMAzlXidThqzyftV8at+qlfSNm8M8gqvzen0AUEV4lvsXAvmBJF0GQBkh5JP1I3XDUvd60sWEglC4+KRsnv5d+pcov ZErw8ekgl7y6fM3gYaOuFDcqN0iaV2F2PAOM4jDTjH9M8 = "}, "MSG", "login successful!" }Copy the code


  • conclusion

    • The Connect () function of HttpURLConnection actually establishes a TCP connection to the server without actually sending an HTTP request. Whether it’s post or GET, HTTP requests aren’t actually sent out until the getInputStream() function of HttpURLConnection.
    • When sending URL requests via POST, the order in which URL request parameters are set is of Paramount importance, and all configuration of the Connection object (the set functions) must be done before connect() is executed. Write to outputStream must precede read to inputStream. These orders are actually determined by the format of the HTTP request.
    • An HTTP request actually consists of two parts: the HTTP header, where all the configuration of the HTTP request is defined, and the body content. The connect() function generates HTTP headers based on the configuration value of the HttpURLConnection object, so you must have all the configuration in place before calling Connect.
    • The HTTP header is followed by the body of the HTTP request, which is written to an outputStream. The outputStream is not actually a network stream, but a string stream, and what is written to it is not immediately sent to the network, but stored in memory buffers. When the outputStream is closed, the HTTP body is generated based on the input. At this point, everything for the HTTP request is in place. When getInputStream() is called, the prepared HTTP request is formally sent to the server and an input stream is returned to read the server’s response to the HTTP request. Since the HTTP request has already been sent by getInputStream (both HTTP headers and body), Therefore, there is no point in setting the Connection object (modifying the HTTP header information) or writing the outputStream (modifying the body) after getInputStream(). Doing so will result in an exception.
  • Analysis of the

HttpURLConnection is a standard network request utility class provided by the Java layer, which can achieve a variety of functions. From the above code and the result of the returned request, we know that in Android, whatever network request framework is implemented in the same way at the bottom. We can continue to encapsulate this and refine it to become a lightweight Android web request framework.