博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iphone网络交互json实现
阅读量:6453 次
发布时间:2019-06-23

本文共 2891 字,大约阅读时间需要 9 分钟。

/**

 * url:请求地址
 * verb:请求方式
 * parameters:请求参数
 */
+(NSString *)sendRequestTo:(NSURL *)url usingVerb:(NSString *)verb withParameters:(NSDictionary *)parameters{
    NSString *jsonStr = nil;
    NSData *body = nil;
    NSMutableString *params = nil;
    NSString *contentType = @"text/html; charset=utf-8";
    NSURL *finalURL = url;
    if(nil != parameters){
        params = [[NSMutableString alloc] init];
        for(id key in parameters){
            NSString *encodedkey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            CFStringRef value = (CFStringRef)[[parameters objectForKey:key] copy];
            CFStringRef encodedValue = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, value,NULL,(CFStringRef)@";/?:@&=+$", kCFStringEncodingUTF8);
            [params appendFormat:@"%@=%@&", encodedkey, encodedValue];
            CFRelease(value);
            CFRelease(encodedValue);
        }
        [params deleteCharactersInRange:NSMakeRange([params length] - 1, 1)];
    }
    //
    if([verb isEqualToString:@"POST"]){
        contentType = @"application/x-www-form-urlencoded; charset=utf-8";
        body = [params dataUsingEncoding:NSUTF8StringEncoding];
    }else{
        if(nil != parameters){
            NSString *urlWithParams = [[url absoluteString] stringByAppendingFormat:@"?%@", params];
            finalURL = [NSURL URLWithString:urlWithParams];
        }
    }
    NSMutableDictionary *headers = [[[NSMutableDictionary alloc] init] autorelease];
    [headers setValue:contentType forKey:@"Content-Type"];
    [headers setValue:@"text/html" forKey:@"Accept"];
    [headers setValue:@"no-cache" forKey:@"Cache-Control"];
    [headers setValue:@"no-cache" forKey:@"Pragma"];
    [headers setValue:@"close" forKey:@"Connection"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:verb];
    [request setAllHTTPHeaderFields:headers];
    if(nil != parameters){
        [request setHTTPBody:body];
    }
    [params release];
    //
    NSURLResponse *response;
    NSError *error = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if(error){
        NSLog(@"something is wrong: %@", [error description]);
    }else{
        if(responseData){
            jsonStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        }
    }
    return  jsonStr;
}
+(void)testRequest{
    NSLog(@"test request...");
    NSString *getUrl = @"";
    NSString *postUrl = @"";
    NSMutableDictionary *dlist = [[NSMutableDictionary alloc] init];
    [dlist setObject:@"pig" forKey:@"uid"];
    [dlist setObject:@"access token" forKey:@"AccessToken"];
    [dlist setObject:@"access token secret" forKey:@"AccessTokenSecret"];
    NSString *jsonStrGet = [NetAPI sendRequestTo:[NSURL URLWithString:getUrl] usingVerb:@"GET" withParameters:dlist];
    NSLog(@"do get: jsonStrGet = %@", jsonStrGet);
    NSString *jsonStrPost = [NetAPI sendRequestTo:[NSURL URLWithString:postUrl] usingVerb:@"POST" withParameters:dlist];
    NSLog(@"do post: jsonStrPost = %@", jsonStrPost);
    [dlist release];
}

转载地址:http://ipyzo.baihongyu.com/

你可能感兴趣的文章
3.2 采购管理目标
查看>>
Unity3d地形刷入自定义树木
查看>>
BZOJ2434【NOI2011】阿狸的打字机 <AC自动机+Fail树+树状数组>
查看>>
DotNetTextBox V3.0 所见即所得编辑器控件 For Asp.Net2.0(ver 3.1.1Beta)
查看>>
第十一节:WebApi的版本管理的几种方式
查看>>
[转] React同构思想
查看>>
MySQL_视图/触发器/事务/存储过程/函数
查看>>
Delphi_时间间隔
查看>>
让年轻程序员少走弯路的14个忠告
查看>>
null 和System.DBNull.Value
查看>>
marxico完败其他markdown编辑器的几个特性
查看>>
(3)事件
查看>>
操作系统详解
查看>>
数据库的并发操作与数据的不一致性
查看>>
git 远程仓库自动更新
查看>>
ArcEngine数据入库工具界面
查看>>
mysql join优化原理
查看>>
聪明的质检员
查看>>
[javascript|基本概念|Underfined]学习笔记
查看>>
jquery 笔记
查看>>