您的位置:首页 > Web前端 > JavaScript

与Server端进行Json数据的POST操作

2015-04-16 13:00 288 查看
由于最近项目在网络通信方面需要传输Json格式,所以在网上搜索了一下关于Json的数据传输:关于AFNetWorking的很多例子不可用,经过搜集资料,最终调通了与Server的信息交互,具体交互方式如下,亲测可行:

1:ASI与Server的交互。

NSMutableDictionary *myArray = @{@"imei":@"napq3MyaOOUjaU6necZ5lDLslmQ=",@"imsi":@"AlUAwfYVf3ZGiFZZDVruer7cW4Q=",@"wifiSSID":@"112233",@"osVersion":@"Android4.1.2",@"mobileID":@"1112733557413931973",@"channelID":@"4139823094061327276",@"deviceName":@"HUAWEIG730-C00",@"date":@"12345678",@"id":@"112233"};

NSMutableDictionary *jsonDic = [NSMutableDictionarydictionary];
[jsonDicsetObject:myArray
forKey:@"deviceInfo"];
[jsonDicsetObject:@"juexing"forKey:@"name"];

[jsonDic setObject:@"15800000000"forKey:@"mobile"];
[jsonDicsetObject:@"1.0"forKey:@"version"];
NSString *strJson = [jsonDic
JSONString];
NSLog(@"%@",strJson);
NSError *error;

if ([NSJSONSerializationisValidJSONObject:jsonDic])
{

NSData *jsonData = [NSJSONSerializationdataWithJSONObject:jsonDic
options:NSJSONWritingPrettyPrintederror: &error];
NSMutableData *tempJsonData = [NSMutableDatadataWithData:jsonData];

ASIHTTPRequest *request = [ASIHTTPRequestrequestWithURL:url];

[request addRequestHeader:@"Content-Type"value:@"application/json;
encoding=utf-8"];

[request addRequestHeader:@"Accept"value:@"application/json"];
[requestsetRequestMethod:@"POST"];
[requestsetPostBody:tempJsonData];
request.delegate =self;
[requestsetTimeOutSeconds:10];
//超时
[requeststartSynchronous];
NSError *error1 = [request
error];
if (!error1) {
applyresponse = [requestresponseString];
NSLog(@"Test:%@",applyresponse);

}
}
2:AFNetWorking与Server交互。

NSMutableDictionary *dic = [NSMutableDictionarydictionary];
[dicsetObject:myArray
forKey:@"deviceInfo"];

[dic setObject:@"juexing"forKey:@"name"];

[dic setObject:@"15800000000"forKey:@"mobile"];

[dic setObject:@"1.0"forKey:@"version"];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];

manager.requestSerializer = [AFJSONRequestSerializerserializer];

manager.responseSerializer = [AFImageResponseSerializerserializer];

[manager.requestSerializersetValue:@"application/json"forHTTPHeaderField:@"application/json;
encoding=utf-8"];

[manager.requestSerializersetValue:@"application/json"forHTTPHeaderField:@"Accept"
];

manager.responseSerializer.acceptableContentTypes = [NSSetsetWithObject:@"application/json"];

[manager POST:[NSStringstringWithFormat:@"%@",url]parameters:dic
success :^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"json--:%@",operation.responseString);
NSLog(
@"JSON====: %@" , responseObject);

NSDictionary *dicPara = [NSJSONSerializationJSONObjectWithData:operation.responseDataoptions:NSJSONReadingAllowFragmentserror:nil];
NSLog(@"dic---%@",dicPara);

} failure :^(AFHTTPRequestOperation *operation,NSError *error) {

NSLog (
@"Error====: %@" , error. description );
NSLog(
@" 返回值 :%@" ,operation.responseString);

}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐