android uses HttpUrlConnection to access the network

  1.  Declare network access in AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET"/>
  2.  Create a new URL object based on the String type
  3. Cast the URL object to HttpURLConnection type and use the openConnection method to open the link
  4. Set read and connect timeouts for links
  5. Set the request method to GET
  6. Get the input stream InputStream from the link
  7. Set buffer, use buffer as loop variable, read and write input stream to ByteArrayOutputStream
  8. Localization of network input by passing in the result of the String constructor ByteArrayOutputStream.toArray() method

Here is the code sample:

InputStream is = null;
		ByteArrayOutputStream baos = null;
		try {
			URL netUrl = new URL(url); //2
			// open a link
			HttpURLConnection conn = (HttpURLConnection) netUrl.openConnection(); //3
			conn.setReadTimeout(5*1000);
			conn.setConnectTimeout(5*1000); //4
			conn.setRequestMethod("GET"); //5
			
			is = conn.getInputStream(); //6
			int len ​​= -1;
			byte[] buffer = new byte[128]; //7
			baos = new ByteArrayOutputStream();
			//read input stream
			while((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.flush(); //Clear the buffer
			result = new String(baos.toByteArray()); //8 Input stream localization
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} finally {
			// lose all the resources!!
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
			}
		}

 The operation of each step corresponds to the serial number in the comment.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484106&siteId=291194637