Lesson Plan: Unit - 07
Subject: P15A2AAD - Android Application Development
Topic of Study: Accessing the Internet (HTTP)
Grade/Level: Master of Computer Applications
Objective: Accessing the Internet (HTTP)
Time Allotment: 55 Minutes
Subject: P15A2AAD - Android Application Development
Topic of Study: Accessing the Internet (HTTP)
Grade/Level: Master of Computer Applications
Objective: Accessing the Internet (HTTP)
Time Allotment: 55 Minutes
- Accessing the Internet (HTTP)
- To transfer data to and from the network – we use HTTP.
- You can use HTTP to encapsulate almost any type of data and to secure the data with SSL.
- SSL very useful when you transfer data that falls with privacy requirements.
- HTTP protocol typically open from the phone network.
- Read data from the Web.
- Using HttpURLConnection:
- We can use the HttpURLConnection object to do a little reconnaissance on our URL before we transfer too much data.
- HttpURLConnection retrieves some information about the resource referenced by the URL object, including HTTP status and header information.
- You can retrieve from the HttpURLConnection includes
- The length of the content, content type, and date-time information.
- Example:
- Create a URL instance.
- URL url = new URL("http://www.yahoo.com");
- Open url connection and cast it to HttpURLConnection.
- HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
- Set request method. The request method can be GET, POST, DELETE etc. Request method must be uppercase, otherwise below exception will be thrown.
- httpConn.setRequestMethod("GET");
- If request method is GET, then use below code to open input stream and read server response data.
- InputStream inputStream = httpConn.getInputStream();
- InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
- String line = bufferedReader.readLine();
- For POST request method, use below code to open output stream to the server url and write post data to it. After post, open the input stream again to get server response.
- OutputStream outputStream = httpConn.getOutputStream();
- OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
- BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
- bufferedWriter.write("user=ampics&pasword=ampics");
- After use HttpURLConnection, do not forget close related reader or writer and call HttpURLConnection’s disconnect() method to close the connection to release network resources.
- httpConn.disconnect();