根据参数远程获取不同的数据
2011-08-16 15:41
399 查看
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,retain) IBOutlet 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 !
运行环境: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,retain) IBOutlet 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 !
相关文章推荐
- 前端获取到后端数据后,要根据数据类型传输不同的属性值到后端,后端完成特殊业务处理
- 【FileExplorer】文件管理器--------根据不同分类来获取对应的数据
- Web报表finereport根据参数将数据存入不同的数据库
- 根据不同的实体及其ID来获取数据库中的数据
- 根据存储过程参数是否为空获取不同的数据集
- 表单中多个请求参数名字相同,服务器到底获取的是哪个请求参数的值,表单的action和get和post提交方式的关系以及提交数据的不同点
- 总结!根据URI的不同来实现本地和远程的连接对象的获取 3ff8
- SQL 游标使用的小例子,对于每行数据根据参数的不同进行Insert或Update操作.
- C# 解析百度天气数据,Rss解析百度新闻以及根据IP获取所在城市
- Spring MVC根据请求后缀返回不同数据格式
- 根据url 参数,页面显示不同背景图片
- php根据出生日期获取年龄,生日数据类型为date型
- 根据模型中的参数数量判断需要的训练数据的数量
- 图像获取(根据路径或从相册获取后从uri获取路径)、压缩(参数路径或Bitmap)、旋转角度、图像保存
- 2013.11.28数据仓库和事务处理系统的不同(物理底层参数)
- 步步为营VS 2008 + .NET 3.5(13) - DLINQ(LINQ to SQL)之用户自定义函数、在不同的DataContext之间做更新、缓存、获取信息、数据加载选项和延迟加载
- 使用loadrunner11配置参数时,从oracle数据库中获取数据的方法
- 【小平工作日志】Maven根据不同环境打包, 获取不同的配置文件
- 存储过程根据ouID获取IntlPerson数据表
- VB.NET中根据DataGridView中显示的数据条件数据行显示不同的颜色