如何在http post body上发布json字符串?在对象 c
Posted
技术标签:
【中文标题】如何在http post body上发布json字符串?在对象 c【英文标题】:How to post json string on http post body ? in obj c 【发布时间】:2015-10-20 06:54:43 【问题描述】:您好,我是 ios 开发新手,我想通过 http post 请求在我的 Web 服务上发送一些 json 数据,其中数据将在请求正文中而不是在参数中?
感谢任何帮助,谢谢。
【问题讨论】:
Sending a JSON via POST in NSURLRequest的可能重复 【参考方案1】:试试这个代码
NSURL *url = [NSURL URLWithString:@"Your Json URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData in string : %@",str);
NSMutableDictionary *dictTemp = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(@"responseData in Dictionary : %@",dictTemp);
【讨论】:
【参考方案2】:> Try this code
-(void)answerCode
NSError * error ;
NSURLResponse * urlResponse;
NSURL * postUrl =[NSURL URLWithString:YourUrl];//enter your url
//your body here
NSString * body =[NSString stringWithFormat:@"email=dharasis"];
NSMutableURLRequest * request =[[NSMutableURLRequest alloc]initWithURL:postUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:50];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
NSData * data =[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (!data)
return;
id json =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Json result is:%@",josn);
【讨论】:
以上是关于如何在http post body上发布json字符串?在对象 c的主要内容,如果未能解决你的问题,请参考以下文章