Translate

2015年11月11日 星期三

json post/ get

Get

NSString *url="http://www/getid/id=123";
NSString *result= [self Get:url];


Post - List<string> Data

NSString *url="http://www/post/update";
NSMutableArray *list = [[NSMutableArray alloc]init];
[list addObject:name];      //name is NSString
[list addObject:mobile];    //mobile is NSSTring
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:list options:0 error:nil];
NSString *result= [self Post:url value:jsonData];


Funtion

- (NSString*) Post:(NSString*)url
             value:(NSData*)requestData
{
    
    NSURL *theURL = [NSURL URLWithString:url];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    theRequest.timeoutInterval=10.0;
    [theRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPBody: requestData];

    return [self HttpResult:theRequest];
}

-(NSString*) HttpResult:(NSURLRequest*) urlRequest
{

    NSURLResponse *resp = nil;
    NSError *err = nil;
    
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
                                         returningResponse:&resp
                                                     error:&err];
    
    if([data length]>0 && err == nil)
    {
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    else
    {
        return @"nowifi";
    }
    return @"";

}

沒有留言:

張貼留言