Download presentation
Presentation is loading. Please wait.
Published byMargery Pope Modified over 8 years ago
1
CS499 – Mobile Application Development Fall 2013 Networking & HTTP
2
Networking Many applications provide and use data & services via the Internet Lots of different protocol involved in using the data & services: HTTP, FTP, SMTP, POP3, … Android provides several network support classes: – java.net – Socket, URL – org.apache – HttpRequest, HttpResponse – android.net – URI, AndroidHttpClient, AudioStream, …
3
Networking Typically need permission to access the internet: Use for all examples in these slides http://developer.android.com/training/basics/n etwork-ops/index.html
4
private static final String DEBUG_TAG = "NetworkStatusExample";... ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isWifiConn = networkInfo.isConnected(); networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isMobileConn = networkInfo.isConnected(); Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn); Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn); http://developer.android.com/training/basics/network-ops/managing.html
5
Managing Networking Ex: Wifi WifiManager - the primary API for managing all aspects of Wi-Fi connectivity Context.getSystemService(Context.WIFI_SERVI CE) – get an instance of WifiManager. http://developer.android.com/reference/andr oid/net/wifi/WifiManager.html http://developer.android.com/reference/andr oid/net/wifi/WifiManager.html
6
WiFiManager handles: The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified. The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried. Results of access point scans, containing enough information to make decisions about what access point to connect to. It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.
7
WifiManager wifiManager = (WifiManager)getSystemService( Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { wifiText.setText("Wifi Enabled"); } else { wifiText.setText("Wifi Not Enabled"); The permission you will need to set is "android.permission.ACCESS_WIFI_STATE"
8
WebView If you only want to display information inside your app as it would be displayed by a browser, use WebView: … WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnable d(true); webview.loadUrl(“http://www.google.com”); setContentView(webview); …
9
Android Example: HttpURLConnection public class NetworkingURLActivity extends Activity { TextView mTextView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.textView1); new HttpGetTask().execute("https://foundry.test- socrata.com/resource/earthquakes.xml?%24where=magnitude%20%3E%203.0"); } private void onFinishGetRequest(String result) { mTextView.setText(result); } …
10
private class HttpGetTask extends AsyncTask { @Override protected String doInBackground(String... params) { StringBuffer data = new StringBuffer(); BufferedReader br = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(params[0]).openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String rawData; while ((rawData = br.readLine()) != null) { data.append(rawData); } } catch (MalformedURLException e1) {e1.printStackTrace(); } catch (IOException e1) {e1.printStackTrace(); } finally { if (br != null) try { br.close(); } catch (IOException e) {e.printStackTrace();} } return data.toString(); } @Override protected void onPostExecute(String result) { onFinishGetRequest(result); }
12
Parsing HTTP responses Several popular formats including XML, JSON JSON – JavaScript Object Notation – http://www.json.org/ – Intended to be a lightweight data interchange format – Data packaged in two types of structures: Maps of key/value pairs Ordered lists of values
13
JSON Example https://foundry.test- socrata.com/resource/earthquakes.json?%24where=magnitu de%20%3E%203.0 https://foundry.test- socrata.com/resource/earthquakes.json?%24where=magnitu de%20%3E%203.0 Produces a series of records with key/value pairs
14
Parsing JSON Can write your own parser Can use built-in parser for this format: private class HttpGetTask extends AsyncTask<String, Void, List > { @Override protected List doInBackground(String... params) { AndroidHttpClient client = AndroidHttpClient.newInstance(""); HttpGet request = new HttpGet(params[0]); JSONResponseHandler responseHandler = new JSONResponseHandler(); try { return client.execute(request, responseHandler); …
15
private class JSONResponseHandler implements ResponseHandler > { @Override public List handleResponse(HttpResponse response) throws ClientProtocolException, IOException { List result = new ArrayList (); String JSONResponse = new BasicResponseHandler().handleResponse(response); try { JSONObject object = (JSONObject) new JSONTokener(JSONResponse).nextValue(); JSONArray earthquakes = object.getJSONArray("earthquakes"); for (int i = 0; i < earthquakes.length(); i++) { JSONObject tmp = (JSONObject) earthquakes.get(i); result.add("mag:" + tmp.get("magnitude") + " lat:" + tmp.getString("latitude") + " lng:" + tmp.get(“longitude")); } } catch (JSONException e) { e.printStackTrace(); } return result; }
16
XML Example https://foundry.test- socrata.com/resource/earthquakes.xml?%24where=magnitud e%20%3E%203.0 https://foundry.test- socrata.com/resource/earthquakes.xml?%24where=magnitud e%20%3E%203.0
17
Parsing XML More complicated than JSON Several types of parsers available: – SAX – Pull – Application iterates over XML entries – DOM – Converts document into a tree of nodes
18
Using SAX private class HttpGetTask extends AsyncTask > { @Override protected List doInBackground(String... params) { AndroidHttpClient client = AndroidHttpClient.newInstance(""); HttpGet request = new HttpGet(params[0]); XMLResponseHandler responseHandler = new XMLResponseHandler(); try { return client.execute(request, responseHandler);
19
Connecting wirelessly Service Discovery Service Connection Service Registration/Deregistration http://developer.android.com/training/conne ct-devices-wirelessly/index.html http://developer.android.com/training/conne ct-devices-wirelessly/index.html
20
WiFi Direct API 14 and above The Wi-Fi Direct™ APIs allow applications to connect to nearby devices without needing to connect to a network or hotspot. This allows your application to quickly find and interact with nearby devices, at a range beyond the capabilities of Bluetooth. http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html
21
WiFi In order to use Wi-Fi Direct, add permissions to your manifest. Note: Wi-Fi Direct doesn't require an internet connection, but it does use standard Java sockets, which require INTERNET permission.
22
Using Wifi You need to listen for broadcast intents that tell your application when certain events have occurred. Instantiate an IntentFilter and set it to listen for the following: private final IntentFilter intentFilter = new IntentFilter();... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); … // Indicates a change in the Wi-Fi Peer-to-Peer status. intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); // Indicates a change in the list of available peers. intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); // Indicates the state of Wi-Fi P2P connectivity has changed. intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); // Indicates this device's details have changed. intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);... }
23
WifiP2pManager Channel mChannel; WifiP2pManager mManager; public void onCreate(Bundle savedInstanceState) {.... // g et an instance of the WiFiP2pManager and call its initialize() method. // This method returns a WifiP2pManager.Channel object, which // you'll use to connect your app to the Wi-Fi Direct Framework. mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); }
24
/** register the BroadcastReceiver with the intent values to be matched. Will need to implement onReceive() */ @Override public void onResume() { super.onResume(); receiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this); registerReceiver(receiver, intentFilter); } @Override public void onPause() { super.onPause(); unregisterReceiver(receiver); }
25
Peer Discovery mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // Code for when the discovery initiation is successful goes here. // No services have actually been discovered yet, so this method // can often be left blank. Code for peer discovery goes in the // onReceive method, detailed below. } @Override public void onFailure(int reasonCode) { // Code for when the discovery initiation fails goes here. // Alert the user that something went wrong. } });
26
Peer Discovery private List peers = new ArrayList();... private PeerListListener peerListListener = new PeerListListener() { @Override public void onPeersAvailable(WifiP2pDeviceList peerList) { // Out with the old, in with the new. peers.clear(); peers.addAll(peerList.getDeviceList()); // If an AdapterView is backed by this data, notify it // of the change. For instance, if you have a ListView of available // peers, trigger an update. ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged(); if (peers.size() == 0) { Log.d(WiFiDirectActivity.TAG, "No devices found"); return; } } }
27
Connecting to a peer @Override public void connect() { // Picking the first device found on the network. WifiP2pDevice device = peers.get(0); WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; config.wps.setup = WpsInfo.PBC; mManager.connect(mChannel, config, new ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. // Ignore for now. } @Override public void onFailure(int reason) { Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.", Toast.LENGTH_SHORT).show(); } }); }
28
@Override public void onConnectionInfoAvailable(final WifiP2pInfo info) { // InetAddress from WifiP2pInfo struct. InetAddress groupOwnerAddress = info.groupOwnerAddress.getHostAddress()); // After the group negotiation, we can determine the group owner. if (info.groupFormed && info.isGroupOwner) { // Do whatever tasks are specific to the group owner. // One common case is creating a server thread and accepting // incoming connections. } else if (info.groupFormed) { // The other device acts as the client. In this case, // you'll want to create a client thread that connects to the group // owner. }
29
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // Determine if Wifi Direct mode is enabled or not, alert // the Activity. int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { activity.setIsWifiP2pEnabled(true); } else { activity.setIsWifiP2pEnabled(false); } } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { // Request available peers from the wifi p2p manager. This is an // asynchronous call and the calling activity is notified with a // callback on PeerListListener.onPeersAvailable() if (mManager != null) { mManager.requestPeers(mChannel, peerListener); } Log.d(WiFiDirectActivity.TAG, "P2P peers changed"); } } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { if (mManager == null) { return; } NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); if (networkInfo.isConnected()) { // We are connected with the other device, request connection // info to find group owner IP mManager.requestConnectionInfo(mChannel, connectionListener); } BroadcastReciever code
30
Android Example: Sockets public class NetworkingSocketsActivity extends Activity { TextView mTextView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.textView1); // assuming webserver running on local machine with given IP address new HttpGet().execute(" 129.174.93.161 "); } private void onFinishGetRequest(String result) { mTextView.setText(result); }
31
private class HttpGet extends AsyncTask { @Override protected String doInBackground(String... params) { Socket socket = null; StringBuffer data = new StringBuffer(); try { socket = new Socket(params[0], 80); PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true); pw.println("GET /~white/testfile"); BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream())); String rawData; while ((rawData = br.readLine()) != null) { data.append(rawData); } } catch (UnknownHostException e1) {e1.printStackTrace(); } catch (IOException e1) {e1.printStackTrace(); } finally {if (null != socket) try { socket.close(); } catch (IOException e) {e.printStackTrace();} return data.toString(); } @Override protected void onPostExecute(String result) { onFinishGetRequest(result); } }
32
http example Suppose user enters URL www.someSchool.edu/someDepartment/home.index 1a. http client initiates TCP connection to http server (process) at www.someSchool.edu. Port 80 is default for http server. 2. http client sends http request message (containing URL) into TCP connection socket 1b. http server at host www.someSchool.edu waiting for TCP connection at port 80. “accepts” connection, notifying client 3. http server receives request message, forms response message containing requested object (someDepartment/home.index ), sends message into socket time Assume contains text, references to 10 jpeg images
33
http example (cont.) 5. http client receives response message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects 6. Steps 1-5 repeated for each of 10 jpeg objects 4. http server closes TCP connection. time
34
http message format: request two types of http messages: request, response http request message: – ASCII (human-readable format) GET /somedir/page.html HTTP/1.0 User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg Accept-language:fr (extra carriage return, line feed) request line (GET, POST, HEAD commands) header lines Carriage return, line feed indicates end of message
35
http request message: general format
36
Examples of a complete client request Example1: GET / HTTP/1.1 Example2: HEAD / HTTP/1.1 Accept: */* Connection: Keep-Alive Host: somehost.com User-Agent: Generic
37
Examples of a complete client request Example3: POST /servlet/myServer.servlet HTTP/1.0 Accept: */* Connection: Keep-Alive Host: somehost.com User-Agent: Generic Name=donald&email=donald@someU.edu
38
http message format: response HTTP/1.0 200 OK Date: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 …... Content-Length: 6821 Content-Type: text/html data data data data data... status line (protocol status code status phrase) header lines data, e.g., requested html file
39
http response status codes 200 OK – request succeeded, requested object later in this message 301 Moved Permanently – requested object moved, new location specified later in this message (Location:) 400 Bad Request – request message not understood by server 404 Not Found – requested document not found on this server 505 HTTP Version Not Supported In first line in server->client response message. A few sample codes:
40
Trying out http (client side) for yourself 1. Telnet to your favorite Web server: Opens TCP connection to port 80 (default http server port) Anything typed in sent to port 80 at this site telnet www.cs.gmu.edu 80 2. Type in a GET http request: GET /~white/testfile HTTP/1.0 By typing this in (hit carriage return twice), you send this minimal (but complete) GET request to http server 3. Look at response message sent by http server!
41
Same thing in C #include void error(char *msg) { perror(msg); exit(0); } int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[1024]; portno = 80; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); server = gethostbyname("osf1.gmu.edu"); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); bzero(buffer,1024); sprintf(buffer,"GET /~white/ HTTP/1.0\n\n"); n = write(sockfd,buffer,strlen(buffer)); if (n < 0) error("ERROR writing to socket"); bzero(buffer,1024); n = read(sockfd,buffer,1023); if (n < 0) error("ERROR reading from socket"); printf("%s\n",buffer); close(sockfd); return 0; }
42
A Basic Java HTTP Client implementation InetAddress host = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); String fileName = args[2].trim(); String request = "GET " + fileName + " HTTP/1.0\n\n"; MyStreamSocket mySocket = new MyStreamSocket(host, port); mySocket.sendMessage(request); // now receive the response from the HTTP server String response = mySocket.receiveMessage(); // read and display one line at a time while (response != null) { System.out.println(response); response = mySocket.receiveMessage(); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.