- Declare network access in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
- Create a new URL object based on the String type
- Cast the URL object to HttpURLConnection type and use the openConnection method to open the link
- Set read and connect timeouts for links
- Set the request method to GET
- Get the input stream InputStream from the link
- Set buffer, use buffer as loop variable, read and write input stream to ByteArrayOutputStream
- 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.