• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

iOS网络开发-AFNetworking请求asp.netWebService

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

看到园子有位朋友需要使用AFN框架请求 WebService,所以就整理了一下,demo下载链接在底部

编写WebService可以看这篇博客 http://www.cnblogs.com/linmingjun/p/4606451.html

//使用AFN请问无参方法

//使用AFN无参
-(void)AfnDemo
{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://115.231.54.166:9090/JobRecordAPP.asmx/QueryWeather"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0f];
    AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        //返回字符串
        NSString *html = operation.responseString;
        NSLog(@"html----%@",html);
        //将返回字符串头去掉:<?xml version=\"1.0\" encoding=\"utf-8\"?>
        NSString *str =@"<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        NSString *strhtml =[html stringByReplacingOccurrencesOfString:str withString:@""];
        //将返回字符串头去掉
        strhtml = [strhtml stringByReplacingOccurrencesOfString:@"<string xmlns=\"http://tempuri.org/\">" withString:@""];
        //将返回的字符串尾去掉
        strhtml = [strhtml stringByReplacingOccurrencesOfString:@"</string>" withString:@""];
        //去掉结尾空格
        NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        strhtml= [[NSString alloc]initWithString:[strhtml stringByTrimmingCharactersInSet:whiteSpace]];
        NSLog(@"无参----%@",strhtml);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self initFailure];
    }];
    [operation start];
}
//使用AFN有参
-(void)AfnDemo2:(NSString *)catObj
{

    NSString *url = @"http://115.231.54.166:9090/JobRecordAPP.asmx/BrowseStatistics?";
//设置参数 NSString
*k_initUrl3 =[url stringByAppendingFormat:@"LoginID=%@",catObj]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:k_initUrl3] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0f]; AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSString *html = operation.responseString; //将返回字符串头去掉:<?xml version=\"1.0\" encoding=\"utf-8\"?> NSString *str =@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"; NSString *strhtml =[html stringByReplacingOccurrencesOfString:str withString:@""]; //将返回字符串头去掉 strhtml = [strhtml stringByReplacingOccurrencesOfString:@"<string xmlns=\"http://tempuri.org/\">" withString:@""]; //将返回的字符串尾去掉 strhtml = [strhtml stringByReplacingOccurrencesOfString:@"</string>" withString:@""]; //去掉结尾空格 NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; strhtml= [[NSString alloc]initWithString:[strhtml stringByTrimmingCharactersInSet:whiteSpace]]; NSLog(@"有参----%@",strhtml); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { [self initFailure]; }]; [operation start]; }

在使用.Net Web服务编写WebService,如上图我们可以看到返回的数据,前后数据多出了
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">
</string>
所以在得到json格式的数据的时候,先把前后多余的数据给替换了设置为空。
完整案例数据解析过程 NSString->NSData->NSarray
//
-(void)initSetting
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://115.231.54.166:9090/JobRecordAPP.asmx/QueryWeather"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0f];
    AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;
        //将返回字符串头去掉:<?xml version=\"1.0\" encoding=\"utf-8\"?>
        NSString *str =@"<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        NSString *strhtml =[html stringByReplacingOccurrencesOfString:str withString:@""];
        //将返回字符串头去掉
        strhtml = [strhtml stringByReplacingOccurrencesOfString:@"<string xmlns=\"http://tempuri.org/\">" withString:@""];
        //将返回的字符串尾去掉
        strhtml = [strhtml stringByReplacingOccurrencesOfString:@"</string>" withString:@""];
        //去掉结尾空格
        NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        strhtml= [[NSString alloc]initWithString:[strhtml stringByTrimmingCharactersInSet:whiteSpace]];
       
       NSData *data= [strhtml dataUsingEncoding:NSUTF8StringEncoding];
       
        [[ProblemPaperKindObject share] videoWithDict:[data JSONValue]];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self initFailure];
    }];
    [operation start];

}
View Code
ProblemPaperKindObject 课程分类模型类

ProblemPaperKindObject.h

#import <Foundation/Foundation.h>

@interface ProblemPaperKindObject : NSObject
/*!
 *  分类信息
 */
@property(nonatomic,strong) NSArray *categorys;
/*!
 *  显示的分类
 */
@property(nonatomic,strong) NSArray *categorysShow;
@property(nonatomic,strong) NSArray *categoryHide;


@property(nonatomic,strong) NSArray *indexsCategorys;
//类别编号
@property (assign,nonatomic) int PRKID;

//根节点
@property (assign,nonatomic) int ParentID;

//名称
@property (copy,nonatomic) NSString *Name;

- (void)videoWithDict:(NSDictionary *)dict;
- (void)videoWithDict2:(NSDictionary *)dict;
- (void)initWithJson:(NSDictionary *)dict;

+(ProblemPaperKindObject *)share;


@end
View Code
#import "ProblemPaperKindObject.h"
#import "Common.h"
#import "Config.h"
@implementation ProblemPaperKindObject
+(ProblemPaperKindObject *)share
{
    static ProblemPaperKindObject * _ProblemPaperKindObject_Share=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _ProblemPaperKindObject_Share=[[ProblemPaperKindObject alloc] init];
    });
    return _ProblemPaperKindObject_Share;
}
-(void)videoWithDict:(NSArray *)dict
{
    NSMutableArray *categorysTemp=[[NSMutableArray alloc] init];
     for (NSDictionary *dic in dict) {
      //   NSLog(@"videoWithDict---%@",dic[@"Name"]);
         ProblemPaperKindObject *video = [[ProblemPaperKindObject alloc] init];
         video.PRKID = [dic[@"PRKID"] intValue];
         video.ParentID = [dic[@"ParentID"] intValue];
         video.Name = dic[@"Name"];
         [categorysTemp addObject:video];
     }
    self.indexsCategorys=[NSArray arrayWithArray:categorysTemp];
    
    //    [video setValuesForKeysWithDictionary:dict]; // KVC方法使用前提: 字典中的所有key 都能在 模型属性 中找到
    
}
-(void)videoWithDict2:(NSArray *)dict
{
    //分类中分类!
    
    
    NSMutableArray *categorysTemp=[[NSMutableArray alloc] init];
    for (NSDictionary *dic in dict) {
        ProblemPaperKindObject *video = [[ProblemPaperKindObject alloc] init];
        video.PRKID = [dic[@"PRKID"] intValue];
        video.ParentID = [dic[@"ParentID"] intValue];
        video.Name = dic[@"Name"];
         [categorysTemp addObject:video];
            //NSLog(@"PRKID---%@",[dic objectForKey:@"PRKID"]);
        
    }
    self.categorys=[NSArray arrayWithArray:categorysTemp];
    //显示的分类
    NSArray *categoryShowArr=[[Common readLocalString:k_categoryShowPath secondPath:k_categoryShowPath2] JSONValue];
   // NSLog(@"k_DocumentsPath---%@",k_DocumentsPath);
   // NSLog(@"categoryShowArr----%@",categoryShowArr);
    //
   // NSLog(@"categoryShowArr--%@",categoryShowArr);
    
    NSMutableArray *showTempArr=[[NSMutableArray alloc] init];
    for (int i=0; i<categoryShowArr.count; i++) {
        NSPredicate *filter=[NSPredicate predicateWithFormat:@"PRKID=%@",[categoryShowArr objectAtIndex:i]];
        [showTempArr addObjectsFromArray:[self.categorys filteredArrayUsingPredicate:filter]];
    }
    self.categorysShow=[NSArray arrayWithArray:showTempArr];
  //  NSLog(@"categorysShow--%@",self.categorysShow);
    NSPredicate *filter2=[NSPredicate predicateWithFormat:@" NOT (PRKID  in %@)",categoryShowArr];
    self.categoryHide=[self.categorys filteredArrayUsingPredicate:filter2];
    
    
    //    [video setValuesForKeysWithDictionary:dict]; // KVC方法使用前提: 字典中的所有key 都能在 模型属性 中找到
    
}



-(void)initWithJson:(NSDictionary *)dict
{
    [self videoWithDict:dict];
}
@end
View Code
JSON.h

//
//  JSON1.h
//  NewsBrowser
//
//  Created by Ethan on 13-11-17.
//  Copyright (c) 2013年 Ethan. All rights reserved.
//

#import <Foundation/Foundation.h>


@interface NSString (JSON)
- (id) JSONValue;
@end

@interface NSData (JSON)
- (id) JSONValue;
@end

@interface NSObject (JSON)
- (NSString *)JSONRepresentation;
@end



JSON.m



//
//  JSON1.m
//  NewsBrowser
//
//  Created by Ethan on 13-11-17.
//  Copyright (c) 2013年 Ethan. All rights reserved.
//



#import "JSON.h"

@implementation NSString (JSON)
- (id) JSONValue {
    NSError *error = nil;
    id obj = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
    if (error)
        NSLog(@"%@", [error description]);
    return obj;
}
@end



@implementation NSData (JSON)
- (id) JSONValue {
    NSError *error = nil;
    id obj = [NSJSONSerialization JSONObjectWithData:self options:NSJSONReadingMutableContainers error:&error];
    if (error)
        NSLog(@"%@", [error description]);
    return obj;
}
@end

@implementation NSObject (JSON)
- (NSString *)JSONRepresentation
{
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error = nil;
        NSData *data=[NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        if (error)
            NSLog(@"%@", [error description]);
        NSString *result=[[NSString alloc]initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
        return result;
    }
    return @"";
}
@end
View Code

AFNetworking请求WebService Demo下载地址:链接: http://pan.baidu.com/s/1c0i9fS8 密码: 2vt9


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.NET读取本地Excel发布时间:2022-07-10
下一篇:
ASP.NETMVC+Bootstrap个人博客之打造清新分页Helper(三)发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap