第一步,组装json格式的请求参数,得到 jsonData
//创建json格式的请求参数NSError *error = NULL;
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
[txt_ text],@"id",
@"from iphone",@"description"
, nil];
//将NSDictionary格式的数据压缩NSData格式,同时编码成UTF8格式
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:info
options:NSJSONWritingPrettyPrinted
error:&error];
第二步,请求webservice接口(封装为函数):
//直接在里面获取到数据并处理即可
-(void)insertCatalogWithJson:(NSData*)json
{
NSString *urlAsString = [[NSString alloc]initWithString: [kWSLookingFunURL absoluteString]];
urlAsString = [urlAsString stringByAppendingString:@"?action=insert"];
//将string类型url的请求参数封装为NSURL
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
//直接把NSData(此时的编码为UTF8)做为请求参数
[urlRequest setHTTPBody:json];
NSLog(@"REQUEST: %@", [urlRequest HTTPBody]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil)
{
//获得到数据
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
//重新从WebService读取资料
// [self wsLookingFun];
}else if ([data length] == 0 && error == nil)
{
NSLog(@"Nothing was downloaded.");
}else if (error != nil)
{
NSLog(@"Error happened = %@", error);
}
}];
}
第三步,调用函数即可:
[self insertCatalogWithJson:jsonData];