HTTP

Modified

DOWNLOAD

iPhone SDK Development text example

URL Loader example

Calculator Echo Client example (with source code and Echo server).

Client/Server

A Web browser/server are examples of a client/server computer system. The client requests services, the server provides the services. Each follows a strict protocol that defines the rules for interactions between the client and server.

URL - Universal Resource Locator. Specifies a unique identifier to a resource located on a server.

The URL http://www.ius.edu/rwisman/Hello.htm specifies:

  • HTTP protocol
  • Server www.ius.edu
  • Resource rwisman/Hello.htm
Other protocols can be specified in a URL, for example email can be specified using the URL mailto:GWBush@WhiteHouse.gov

 

Client - A computer that accesses shared network resources provided by another computer, called a server. An Internet client application is a program that accesses information from a network data source (server) using Internet protocols such as gopher, FTP, or HTTP. An Internet client application might access a server to retrieve data such as weather maps, stock prices, or newspaper headlines, for example. The Internet client can access the server through an external network (the Internet) or an internal network (sometimes called an intranet).

Web browsers are a common Internet client, providing a graphical interface to resources stored on a Web server. The relationship of a client and server is illustrated by the following diagram. The communication exchange is as follows:

  • Client connects to a server at www.ius.edu.
  • Client sends a request to server as rwisman/Hello.htm
  • Server receives request, retrieves the file Hello.htm and copies the contents of the file back to the client.
  • Client receives server response as the contents of file Hello.htm and renders the contents as Hello World.
Server - In general, refers to a computer that provides shared resources to network users. On a network, a computer running software that provides data and services to clients over the network. The term server can also apply to a software process, such as an Automation server, that similarly sends information to clients and that appears on the same computer as a client process, or even within the same application. On the Internet, refers to a network data source using Internet protocols such as gopher, FTP, or HTTP. In the illustration above, the server provides file resources using the HTTP protocol.

HTTP - The rules for Web browser and server interaction are defined by the HyperText Transfer Protocol (HTTP). HTTP supports basic operations that the client can specify:

  • GET requests a specific resource from the server such as a file. The server returns a status heading, a blank line, followed by the item.
  • HEAD requests item status, the server returns only the status.
  • POST sends data to the server.
  • PUT sends data to the server.
  • DELETE deletes a resource.
The communication exchange listed above would be more accurately specified as an HTTP exchange.
GET /rwisman/Hello.htm HTTP/1.0
HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Tue, 10 Apr 2001 03:37:48 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Tue, 10 Apr 2001 03:35:48 GMT
ETag: "021f556fc1c01:60ca"
Content-Length: 24

<H1>Hello World</H1>

Mimic the Actions of a Browser using TELNET

Web servers and clients adhere to the HTTP protocol for communication. Web servers generally listen for HTTP connections on the well-known port 80 and clients connect to port 80. A computer named localhost with SMTP (Simple Mail Transport Protocol) will listen on port 25 for SMTP connections, and TELNET on port 20. A client connecting to the SMTP server would connect to localhost and port 25.

A Web server running on localhost waits for a client to connect on port 80. A client connects to localhost and port 80 to communicate using HTTP. Browsers by default use port 80 but can use other connection ports (e.g. http://www.ius.edu:6666 would use port 6666 instead of 80, although no server may be listening to port 6666).  Other clients applications can also connect to port 80. For example TELNET normally uses port 20 but can connect to port 80. Since TELNET sends whatever you type to the server and displays whatever the server send back, it can be used as a crude browser.

A browser sends HTTP to the server and the server sends back HTTP and some content such as HTML. The browser then renders the HTML so the browser user sees other than raw HTML. Using TELNET as a browser you need to type the HTTP commands to send to the server and will get back the server response. 

 

To test:

  • Enter the following two lines at the command prompt
  • Line 1 runs TELNET to connect to the www.ius.edu port 80, the port on which the Web server listens. 
  • Line 2 (which doesn't display in the Windows 2000 Telnet) is the HTTP sent to the server requesting the default Web page to be returned. 
  • Line 3 is the blank line at the end of a HTTP command. The remainder is part of the server response.
Using TELNET as a Web Client
 
  1. telnet www.ius.edu 80
  2. GET  /  HTTP/1.0

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Tue, 07 February 2009 10:24:54 GMT
Content-type: text/html
Page-Completion-Status: Normal

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Indiana University Southeast</title>
      :
      :
Connection to host lost.
 

Example: Display file from Web Server to iPhone

The following example downloads a file from a Web server using the HTTP protocol. Points of note are:

  • Accessing Web resources, even though an emulation, real Web resources are accessed.
  • Single thread for UI and network access.
  • NSURLConnection class creates connections.
  • -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate method called when data received on connection.
#import <UIKit/UIKit.h>
@interface URLLoaderViewController : UIViewController  {
	IBOutlet UITextView *urlContentsView;
	IBOutlet UIActivityIndicatorView *activityIndicator;
}
- (void) loadURL;
-(void) appendTextToView: (NSString*) textToAppend;
@end
 @implementation URLLoaderViewController
- (void) loadView {
	[super loadView];
	[activityIndicator stopAnimating];
	[self loadURL];
}

-(void) loadURL {
	urlContentsView.text = @"";                                              // Clear any previous text
	
	NSURL *url = [NSURL URLWithString: @"http://homepages.ius.edu/rwisman"];

	// create request and connection
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];

	NSURLConnection *connection = 
                   [[NSURLConnection alloc] initWithRequest:request delegate: self];

	[connection release];
	[request release];
	[activityIndicator startAnimating];
}

// NSURL callbacks
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

	NSString *newText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

	if (newText != NULL) {
		[self appendTextToView: newText];
		[newText release];
	}
}

- (void) connectionDidFinishLoading: (NSURLConnection*) connection {
	[activityIndicator stopAnimating];
}

-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {
	UIAlertView *errorAlert = [[UIAlertView alloc]
			initWithTitle: [error localizedDescription]
			message: [error localizedFailureReason]
			delegate:nil
			cancelButtonTitle:@"OK"
			otherButtonTitles:nil];
	[errorAlert show];
	[errorAlert release];
	[activityIndicator stopAnimating];
}


-(void) appendTextToView: (NSString*) textToAppend  {
    NSString *oldText = urlContentsView.text;
    urlContentsView.text = [oldText stringByAppendingString: textToAppend];
}
@end

 

Example: GET to interact with HTTP server ASP JavaScript

GET requests to a HTTP server can include variables as part of the URL following a ? delimiter. For example, the following GET includes the <variable, value> pair of first=Ray.

http://homepages.ius.edu/rwisman/Who.asp?first=Ray&last=Wisman

The server executes the Who.asp script:

<%@ LANGUAGE = JavaScript %>
<%
     if (Request("first") == "Ray")
        Response.Write("Hello again Ray");
     else
        Response.Write( "Greetings");
%>

 

responding to the browser by:

Hello again Ray

An iPhone app to do the same need only use the URL

http://homepages.ius.edu/rwisman/Who.asp?first=Ray&last=Wisman

 

 

Calculator echo client

The following implements a Calculator where results are sent as HTTP message to a server, echoed back and displayed.

The two critical HTTP elements are:

  1. Sending a message to the server.

    The protocol and server URL (http://localhost:1490) is the first part of the message, followed by any message data.

    The connection must specify the delegate, in this case self.

    Because HTTP protocol is used, sending string @"7" includes the HTTP protocol data and would be sent as:

    GET /?7.000 HTTP/1.1

    -(void) send: (NSString *) s {
        NSURL *url = [NSURL URLWithString:
                                    [NSString stringWithFormat:
                                        @"http://localhost:1490?%@", s]  ];

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
     
       NSURLConnection *connection = [[NSURLConnection alloc]
                                        initWithRequest:request
                                        delegate: self];
        [connection release];
        [request release];
    }

     

  2. Receiving a message from the server.

    The delegate method over-rides connection: didReceiveData: to receive any message from the server.

    The received message text is assigned to the myView.text object for display.

    - (void)connection:(NSURLConnection *)connection  didReceiveData:(NSData *)data {

         NSString *newText = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
         if (newText != NULL) {
            myView.text = newText;
            [newText release];
         }
    }
CalculatorEchoClientViewController.h
#import <UIKit/UIKit.h>

#import "MyModel.h"

@interface CalculatorEchoClientViewController : UIViewController {
    MyModel *myModel;
    IBOutlet UITextField *myView;
}
   
-(IBAction) run: (id) sender;
   
@end
MyModel.h
#import <Foundation/Foundation.h>

@interface MyModel : NSObject {
   double accumulator;
   double opr;
   char op;
}

-(void) setModel: (char) c;
-(id) init;
-(NSString *) getModel;
@end
CalculatorEchoClientViewController.m
#import "CalculatorEchoClientViewController.h"

@implementation CalculatorEchoClientViewController

- (void) viewDidLoad {
    [super viewDidLoad];
    myModel = [[MyModel alloc] init];
}
-(void) send: (NSString *) s {
    NSURL *url = [NSURL URLWithString:
                                [NSString stringWithFormat:
                                    @"http://localhost:1490?%@", s]  ];

    // create request and connection
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
    NSURLConnection *connection = [[NSURLConnection alloc]
                                    initWithRequest:request
                                    delegate: self];
    [connection release];
    [request release];
}
-(IBAction) run: (id) sender {
    UIButton *uiButton = (UIButton *) sender;
    NSString *title = uiButton.currentTitle;
   
    [myModel setModel: [title characterAtIndex: (NSInteger) 0]];
   
    [self send: [myModel getModel]];
}

// callbacks
- (void)connection:(NSURLConnection *)connection
           didReceiveResponse:(NSURLResponse *)response {
	NSLog (@"connectionDidReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection
          didReceiveData:(NSData *)data {

     NSString *newText = [[NSString alloc] initWithData:data
                                              encoding:NSUTF8StringEncoding];
     if (newText != NULL) {
           myView.text = newText;
           [newText release];
     }
}
- (void) connectionDidFinishLoading: (NSURLConnection*) connection {}

-(void) connection:(NSURLConnection *)connection
                                                       didFailWithError: (NSError *)error {
            UIAlertView *errorAlert = [[UIAlertView alloc]
					initWithTitle: [error localizedDescription]
					message: [error localizedFailureReason]
					delegate:nil
					cancelButtonTitle:@"OK"
					otherButtonTitles:nil];
	[errorAlert show];
	[errorAlert release];
}

- (void)dealloc {
    [myModel release];
    [super dealloc];
}
@end
MyModel.m
#import "MyModel.h"

@implementation MyModel

-(void) setModel: (char) c {
    switch (c) {
        case 'C':
            opr = 0.0;
            accumulator= 0.0;
            break;
        case '+':; case '-':; case '*':; case '/' :
            op = c;
            opr = accumulator;
            accumulator = 0.0;
            break;
        case '=' :
            switch (op) {
                case '+':
                    accumulator = opr + accumulator;
                    break;
                case '-':
                    accumulator = opr - accumulator;
                    break;
                case '*':
                    accumulator = opr * accumulator;
                    break;
                case '/':
                    accumulator = opr / accumulator;
                    break;
                default:
                    break;
            }
            break;
        default:			// assume '0'..'9' digit
            accumulator = accumulator * 10.0 + (c-'0');
            break;
    }
}

-(NSString *) getModel {
    return [NSString stringWithFormat:@"%f", accumulator];
}

-(id) init {
	[super init];
	accumulator=0.0;  opr='\0';
	return self;
}
@end