方法一、使用直接写写入格式
NSURL *url=[NSURLURLWithString:urlString];
NSMutableURLRequest *requests = [[NSMutableURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:50];
[requests setHTTPMethod:@"POST"];
//这是最终的数据格式,只要能够转换成这种格式其他的数据类型均可,但有时候服务器端不能够解析
NSString *postParams = [NSString stringWithFormat:@"{\"token\":\"IOS_Json_Data\",\"account\":\"%@\",\"password\":\"%@\"}",username,password];
NSData *data =[postParamsdataUsingEncoding:NSUTF8StringEncoding];
[requests setValue:[NSStringstringWithFormat:@"%lu",(unsignedlong)data.length]forHTTPHeaderField:@"Content-Length"];
[requests setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
[requests setHTTPBody:data];
方法二、使用AFNetworking框架
AFHTTPClient *httpClient = [[AFHTTPClientalloc] initWithBaseURL:[NSURLURLWithString:@""]];
httpClient.parameterEncoding =AFJSONParameterEncoding;
[httpClient setDefaultHeader:@"Accept"value:@"text/json"];
NSMutableDictionary *params=[[NSMutableDictionaryalloc] init];
[params setObject:username forKey:@"account"];
[params setObject:password forKey:@"password"];
[params setObject:@"token"forKey:@"token"];
[httpClient postPath:urlString parameters:params success:^(AFHTTPRequestOperation *operation,id responseObject){
NSLog(@"params ==%@",params);
NSString *responseStr = [[NSStringalloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", responseStr);
}failure:^(AFHTTPRequestOperation *operation,NSError *error)
{
NSLog(@"[HTTPClient Error]: %@",error); }];
方法三、使用系统自带的方法
NSMutableURLRequest *requests = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:50];
[requests setHTTPMethod:@"POST"];
NSDictionary *jsonDic=[NSDictionarydictionaryWithObjectsAndKeys:@"ios_json_data",@"token",@"testid",@"account",@"testid",@"password",nil];
NSData *data;
if ([NSJSONSerializationisValidJSONObject:jsonDic])
{
NSError *error;
data = [NSJSONSerializationdataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrintederror:&error];
}
[requests setValue:[NSStringstringWithFormat:@"%lu",(unsignedlong)data.length]forHTTPHeaderField:@"Content-Length"];
[requests setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
[requests setHTTPBody:data];