Programming with Android: Network Operations Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.

Slides:



Advertisements
Similar presentations
Programming with Android: Network Operations
Advertisements

Hypertext Transfer PROTOCOL ----HTTP Sen Wang CSE5232 Network Programming.
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Programming with Android: Widgets and Events Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
COEN 445 Communication Networks and Protocols Lab 4
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
1 Java Networking – Part I CS , Spring 2008/9.
1 L52 Networking (1). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Hypertext Transfer Protocol Information Systems 337 Prof. Harry Plantinga.
PL-IV- Group A HTTP Request & Response Header
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Computer Networks  Network - A system of computers interconnected in order to share information.  Data transmission - consists of sending and receiving.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CS378 - Mobile Computing Web - WebView and Web Services.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Cosc 4730 Brief return Sockets And HttpClient (and with AsyncTask) DownloadManager.
Data Streams David Meredith Source Chapter 19 of – Shiffman, D. (2008). Learning Processing. Morgan Kaufmann, Burlington, MA. ISBN:
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
HTTP and Threads. Getting Data from the Web Believe it or not, Android apps are able to pull data from the web. Developers can download bitmaps and text.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Server - Client Communication Getting data from server.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Appendix E: Overview of HTTP ©SoftMoore ConsultingSlide 1.
1 WWW. 2 World Wide Web Major application protocol used on the Internet Simple interface Two concepts –Point –Click.
2: Application Layer 1 Chapter 2: Application layer r 2.1 Principles of network applications  app architectures  app requirements r 2.2 Web and HTTP.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
CS 6401 The World Wide Web Outline Background Structure Protocols.
Project Scenario for OpX. High-level Overview In the Test GUI Controller, opXController, for the opX command there is conceptually a call to an appropriate.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Overview of Servlets and JSP
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Adding network connections. Connecting to the Network To perform the network operations, your application manifest must include the following permissions:
Chapter 4 Request and Response. Servlets are controlled by the container.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Distributed Computing & Embedded Systems Chapter 4: Remote Method Invocation Dr. Umair Ali Khan.
Network Programming. These days almost all devices.
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.
Networking with Java 2.
Networking.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Hyper Text Transfer Protocol
Web APIs API = Application Programmer Interface
// Please Setting App_name to Send Successful
Presentation transcript:

Programming with Android: Network Operations Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna

Luca Bedogni, Marco Di Felice – Network programming with Android 2 Outline Network operations: Download Manager Network operations: HTTP Responses Network operations: HTTP Requests Network operations: HTTP Client Network operations: WebView and WebSettings Network operations: WebView Network operations: TCP/UDP Sockets

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: Network Operations  In order to perform network operations (also the one described earlier), specific permissions must be set on the AndroidManifest.xml.  Failure in setting the permissions will cause the system to throw a run-time exception …

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: Network Operations ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // fetch data } else { // display error }  Before the application attempts to connect to the network, it should check to see whether a network connection is available using getActiveNetworkInfo() and isConnected() …

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: WebView Usage WebView  A View that displays web pages, including simple browsing methods (history, zoom in/out/ search, etc). Implemented by the WebView class public WebView(Context contex) Main methods:  public void loadUrl(String url)  load the HTML page at url  public void loadData(String data, String mimeType, string encoding)  load the HTML page contained in data

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: WebView Usage

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: WebView Usage By default, the WebView UI does not include any navigation button …However, callbacks methods are defined:  public void goBack()  public void goForward()  public void reload()  public void clearHistory()

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: WebView Usage It is possible to modify the visualization options of a WebView through the WebSettings class. public WebSettings getSettings() Some options:  void setJavaScriptEnabled(boolean)  void setBuildInZoomControls(boolean)  void setDefaultFontSize(int)

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: Download Manager DownloadManager  System service that handles long-run HTTP downloads. DownloadManager dm=(DownloadManager) getSystemService(DOWNLOAD_SERVICE);  The client can specify the file to be downloaded through an URI (path).  Download is conducted in background (with retries)  Broadcast Intent action is sent to notify when the download completes.

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: Download Manager Request request=new DownloadManager.Request(Uri.parse(address));  The Request class is used to specify a download request to the Download Manager.  long enqueue(DownloadManager.Request)  Cursor query(DownloadManager.Query)  ParcelFileDescriptor openDownloadedFile(long) Main methods of the DownloadManager

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes HTTP (HyperText Tranfer Protocol): Network protocol for exchange/transfer data (hypertext) Request/Resonse Communication Model  HEAD  GET  POST  PUT  DELETE  TRACE  CONNECT MAIN COMMANDS

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes HTTP (HyperText Tranfer Protocol): Network protocol for exchange/transfer data (hypertext) Two implementations of HTTP Clients for Android:  HTTPClient  Complete extendable HTTP Client suitable for web browser (not supported anymore?)  HTTPUrlConnection  Light-weight implementation, suitable for client-server networking applications (recommended by Google) In both cases, HTTP connections must be managed on a separate thread, e.g. using AsynchTask (not the UI thread!).

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP (Abstract) Classes  HttpClient  Interface for an HTTP client  HttpRequest  Interface for an HTTP request  HttpResponse  Interface for an HTTP response  ResponseHandler  Handler that creates an object from an HTTP Response  HttpContext  Context of the HTTP Request (request+response+data)

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes  HttpClient  Interface for an HTTP client (DefaultHttpClient  implementation of an HttpClient) HttpClient client=new DefaultHttpClient(); Main method: The public method execute(…) performs an HTTP request, and allows to process an HTTP reply from the HTTP server. abstract T execute(HttpUriRequest request, ResponseHandler responseHandler) One of the signature of execute()

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes  HttpRequest  Interface for an HTTP request Two implementations: HttpGet  implements the GET HTTP method HttpPost  Implements the POST HTTP method HttpGet request=new HttpGet(String address); HttpGet request=new HttpGet(URI address);

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes  ResponseHandler  Interface for creating an object from an HttpResponse, obtained after having executed an HttpRequest. public abstract T handleResponse (HttpResponse res) Method to override Generally, is a String (HTML code) …

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes  HttpPost  Implements the POST HTTP method List par=new ArrayList () par.add(new BasicNameValuePair(“name”,”Marco”); HttpEntity postEntity=new UrlEncodedFormEntity(par); request.setEntity(postEntity); Encapsulating a parameter … HttpPost request=new HttpPost(String address); HttpPost request=new HttpPost(URI address);

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes Basic HTTPClient Request-Response Application … HttpClient client=new DefaultHttpClient(); HttpGet request=new HttpGet(); request.setURI(“http// try { client.execute(request, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes Basic HTTPClient Request-Response Application … class MyResponseHandler implements ResponseHandler public String handleResponse(HttpResponse response) { InputStream content=response.getEntity().getContent(); byte[] buffer=new byte[1024]; int numRead=0; ByteArrayOutputStream stream=new ByteArrayOutputStream(); while ((numRead=content.read(buffer))!=-1) stream.write(buffer, 0, numRead); content.close(); String result=new String(stream.toByteArray()); return result; }

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes HTTPUrlConnection  HTTP component to send and receive streaming data over the web. 1. Obtain a new HttpURLConnection by calling the URL.openConnection() URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 2. Prepare the request, set the options (e.g. session cookies) 3. For POST commands, invoke setDoOutput(true). Transmit data by writing to the stream returned by getOutputStream().

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: HTTP Classes HTTPUrlConnection  HTTP component to send and receive streaming data over the web. 4. Read the response (data+header). The response body may be read from the stream returned by getInputStream (). InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 5. Close the session when ending reading the stream through disconnect (). urlConnection.disconnect();

Luca Bedogni, Marco Di Felice – Network programming with Android (c) Luca Bedogni Android: TCP/IP Communication TCP/UDP Communication  Android applications can use java.net.Socket facilities.  Use socket-based programming like in Java … Class DatagramSocket  UDP Socket Classes Socket/ServerSocket  TCP socket Read/Write on Sockets through InputStream/OutputStream