根据参数远程获取不同的数据

iphone根据参数远程从基于.NET的WebServices服务获取对应的数据

运行环境:Xcode 4.1

.NET + WebServices +Handler.ashx 

运行效果如下所示:

单击不同的按钮,远程获取不同的数据,然后填充到UITableView控件中。

1:搭建后台代码

<%@ WebHandler Language="C#" Class="indexHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Text;
public class indexHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "text/plain";
        //初始化数据

        string username = context.Request.Params["type"];//type是用户从iphone客户端传入的参数

        if (string.IsNullOrEmpty(username))
        {
            context.Response.Write("{\"data\":[]}");
            context.Response.End();
        }

        string[] charArrary = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
       
        StringBuilder sb = new StringBuilder();
        sb.Append("{\"data\":");
        sb.Append("[");
        for (int i = 0; i < 10; i++)
        {

            //根据不同的参数,返回与参数对应的数据到iphone客户端
            if (username == "char")
            {
                sb.Append("{\"name\":\"" + charArrary[i] + "\"}");
            }
            else if (username == "number")
            {
                sb.Append("{\"name\":\"" + (i+1).ToString() + "\"}");
            }
            if (i != 9)
            {
                sb.Append(",");
            }
        }
        sb.Append("]");
        sb.Append("}");

        //返回
        context.Response.Write(sb.ToString());
        context.Response.End();
    }

    public class People
    {
        public string Name
        {
            set;
            get;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

2:IPHONE客户端代码

HttpConnection.h //代码如下所示:

#import <Foundation/Foundation.h>

#import "HttpConnectionDelegate.h"

@interface HttpConnection : NSObject { 

NSMutableData *_buf;

BOOL _isHttpResponseOK;

id<HttpConnectionDelegate> connectionDelegate;

}

@property(nonatomic,retain) id<HttpConnectionDelegate> connectionDelegate;

-(void)Send:(NSString *)url params:(NSString *)params;

- (void)postHTTPErrorNotification;

-(NSDictionary *)getHttpHeaders:(long)contentLength;

@end

HttpConnection.m//代码如下所示:

//

//  HttpConnection.m

//  GIILBS

//

//  Created by infohold mac1 on 11-3-2.

//  Copyright 2011 infohold. All rights reserved.

//

#import "HttpConnection.h"

@implementation HttpConnection

@synthesize connectionDelegate;

-(id)init{

if (self=[super init])

{

_isHttpResponseOK=FALSE;

_buf=[[NSMutableData alloc] initWithLength:0];

}

return self;

}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

NSHTTPURLResponse *responseHTTP=(NSHTTPURLResponse *)response;

if (([responseHTTP statusCode]/100)!=2) {

_isHttpResponseOK=FALSE;

}else {

_isHttpResponseOK=TRUE;

}

}

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

[_buf appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

[connection release];

if (_isHttpResponseOK) {

[self release];

}else {

[self postHTTPErrorNotification];

[self release];

}

[connectionDelegate onGetData:_buf];

}

-(void)Send:(NSString *)url params:(NSString *)params{

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

NSData *postData=[params dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

[request setHTTPMethod:@"POST"];

[request setAllHTTPHeaderFields:[self getHttpHeaders:[postData length]]];

[request setHTTPBody:postData];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

url=nil;

params=nil;

}

-(void)postHTTPErrorNotification

{

[[NSNotificationCenter defaultCenter] postNotificationName:@"HE" object:self];

}

- (void)dealloc

{

connectionDelegate=nil;

[_buf release];

    [super dealloc];

}

-(NSDictionary *)getHttpHeaders:(long)contentLength{

NSMutableDictionary *headers=[[NSMutableDictionary alloc] init];

[headers setValue:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];

    [headers setValue:[NSString stringWithFormat:@"%ld",contentLength] forKey:@"Content-Length"];

    [headers setValue:@"MIMEType" forKey:@"Accept"];

    [headers setValue:@"no-cache" forKey:@"Cache-Control"];

return headers;

}

@end

HttpConnectionDelegate.h//参考代码

#import <UIKit/UIKit.h>

@protocol HttpConnectionDelegate

@optional

-(void)onRecivedDataError:(NSData *)data;

-(void)onGetData:(NSData *)data;

@end

connectonTest.h//参考代码

#import <UIKit/UIKit.h>

#import "HttpConnection.h"

@interface connectonTest : UIViewController 

<HttpConnectionDelegate,UITableViewDelegate,UITableViewDataSource>

{

UITableView *m_tableView;

HttpConnection *request;

NSMutableArray *m_array;

}

@property(nonatomic,retainIBOutlet UITableView *m_tableView;

-(IBAction)GoA;

-(IBAction)GoB;

-(void)GetAreasFromData:(NSData *)data;

@end

connectonTest.m//参考代码(部分)

#import "connectonTest.h"

#import "CJSONDeserializer.h"

@implementation connectonTest

@synthesize m_tableView;

-(IBAction)GoA

{

NSString *params=@"type=char";

NSString *url = @"http://192.168.0.103/GIITicketServer/indexHandler.ashx";

request = [[HttpConnection alloc] init];

request.connectionDelegate = self;

[request Send:url params:params];

}

-(IBAction)GoB

{

NSString *params=@"type=number";

NSString *url = @"http://192.168.0.103/GIITicketServer/indexHandler.ashx";

request = [[HttpConnection alloc] init];

request.connectionDelegate = self;

[request Send:url params:params];

}

-(void)onGetData:(NSData *)data

{

[self GetAreasFromData:data];

}

-(void)onRecivedData:(NSData *)data actionIndex:(int)ActionIndex

{

[self GetAreasFromData:data];

}

-(void)GetAreasFromData:(NSData *)data

{

[m_array removeAllObjects];

CJSONDeserializer *jsonDeserializer=[CJSONDeserializer deserializer];

NSDictionary *resultDictionary=[jsonDeserializer deserialize:data error:error];

NSArray *tt = [resultDictionary objectForKey:@"data"];

for (id key in tt)

{

NSDictionary *keyValue  = (NSDictionary *)key;

NSString *ttt = [keyValue objectForKey:@"name"];

[m_array addObject:ttt];

}

[m_tableView reloadData];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

{

return [m_array count];

}

// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @"Cell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    

if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    }

cell.textLabel.text = [m_array objectAtIndex:indexPath.row];

return cell;

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

request = [[HttpConnection alloc] init];

request.connectionDelegate = self;

m_array =[[NSMutableArray alloc] init];

}

- (void)dealloc 

{

[m_array release];

//[request release];

[m_tableView release];

    [super dealloc];

}

connectonTest.xib//文件,如开头的两幅图片所示:

THE END !

原文地址:https://www.cnblogs.com/xingchen/p/2140693.html