發(fā)送json到服務(wù)器
1,如果發(fā)送JSON數(shù)據(jù),比如商城下單的時候發(fā)送下單信息給服務(wù)器,則必須在請求頭中說明數(shù)據(jù)類型
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/order"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSDictionary *orderInfo = @{
@"shop_id":@"12341",
@"shop_name":@"zhang",
@"user_id":@"danfeng"
};
NSData *data01 = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = data01;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@",data);
if(data == nil || connectionError) return ;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
NSString *success = dict[@"success"];
if(error){
NSLog(@"%@",error);
}else{
NSLog(@"%@",success );
}
}];
}
發(fā)送多值參數(shù)到服務(wù)器
2,多值參數(shù),也就是一個參數(shù)中有多個值,直接拼接成字符串放進(jìn)去即可:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/weather"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSMutableString *body = [NSMutableString string];
[body appendString:@"place=beijing"];
[body appendString:@"&place=shanghai"];
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(connectionError || data == nil){
NSLog(@"request failed");
}
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
NSString *weather = dict[@"weathers"];
if(error){
NSLog(@"%@",error);
}else if(weather){
NSLog(@"%@",weather);
}
}];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。