您的位置:首页 > 理论基础 > 计算机网络

ASIHttpRequest的get和post应用

2015-10-24 00:42 453 查看
//http.h全文
#import <Foundation/Foundation.h>

@interface http : NSObject
// 发送带参数webService请求,参数: webServiceURL,参数名,参数值
- (NSString*) synchronousRequest:(NSString*) webServiceURL
paramName:(NSString *) cityName paramValue:(NSString *) cityValue;
// 发送webService请求,无参数
- (NSString*) synchronousRequest:(NSString*) webServiceURL;
@end
//http.m全文
#import "http.h"
#import "ASIHTTPRequest/ASIHTTPRequest.h"
#import "ASIHTTPRequest/ASIFormDataRequest.h"

@implementation http
- (NSString*) synchronousRequest:(NSString*) webServiceURL
{
// 创建NSURL对象
NSURL *url = [NSURL URLWithString:webServiceURL];
// ASIHTTPRequest对象用来发送简单的Get请求
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
// 发送同步请求
[request startSynchronous];
// 通过检查error属性可以判断请求是否成功或发生错误。
NSError *error = [request error];
if (!error)
{
return [request responseString];
}
NSLog(@"发送无参数的GET请求时发生错误:%@", error);
return nil;
}

- (NSString*) synchronousRequest:(NSString*) webServiceURL
paramName:(NSString *) cityName paramValue:(NSString *) cityValue
{
NSURL *url = [NSURL URLWithString:webServiceURL];
// 使用ASIFormDataRequest发送带参数的POST请求
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// 添加请求参数
[request setPostValue:cityValue forKey:cityName];
// 发送同步请求
[request startSynchronous];
// 通过检查error属性可以判断请求是否成功或发生错误。
NSError *error = [request error];
if (!error)
{
return [request responseString];
}
NSLog(@"发送带参数的POST请求时发生错误:%@", error);
return nil;
}
@end

//viewController中的三个按钮的响应函数
//获取市的天气预报
- (IBAction)getCityWeather:(id)sender {

// 创建FKASIHTTPRequestUtil的对象
http *asi = [[http alloc] init];
NSString *city = @"深圳";
// 调用 synchronousRequest方法根据城市名称获取城市的天气信息,返回的是一个xml格式的字符串
NSString *responseString = [asi synchronousRequest:getWeatherbyCityName
paramName:theCityName paramValue:city];
[textview setText:responseString];
// 从远程服务器获取数据 ,免费用户二次获取数据时间要超过600ms,所以此处暂停0.7秒
//[NSThread sleepForTimeInterval:0.7];

return;
}

//获取市列表
- (IBAction)getCityName:(id)sender {

http* asi = [[http alloc] init];
NSString* prov = @"广东";
NSString* responseString = [asi synchronousRequest:getSupportCity paramName:byProvinceName paramValue:prov];
[textview setText:responseString];

return;
}

//获取省列表
- (IBAction)getProvinces:(id)sender {

http* asi = [[http alloc]init];
NSString* responseString = [asi synchronousRequest:getSupportProvince];
//[NSThread sleepForTimeInterval:0.7];
[textview setText:responseString];

return;
}


点击按钮后可以显示接收到的xml字符串,图片使用模拟器截的







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: