我尝试了很多方法将数据发布到服务器,但没有一种方法可以工作,只有响应才是:
{"消息":"发生了错误。"}
以下是我最近尝试过的方法。
NSString *cust_id=@"2";
NSString *Prod_ID=@"18";
NSString *Vend_ID=@"1";
NSString *Quant=@"2";
NSString *post =[NSString stringWithFormat:@"customerid=%@&productid=%@&vendorid=%@&quantity=%@",cust_id,Prod_ID,Vend_ID,Quant];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:@"http://dealnxt.com/api/addtocart"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"str:%@",str);
答案 0 :(得分:0)
BASE_URL = PASS_YOUR_URL _params = parameters // AS NSMutableDictionary 试试这个。
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:YOUR_VALUE forKey:@"cust_id"]; // here pass your field that you want to pass as parameter.
[params setValue:YOUR_VALUE forKey:@"Prod_ID"];
NSString *url = [BASE_URL stringByAppendingString:_action];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:url parameters:_params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"response = %@", responseObject);
if( _success )
{
_success( responseObject ) ;
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@", error);
if( _failure )
{
_failure( error) ;
}
}];
答案 1 :(得分:0)
您正在传递查询字符串中的数据,因为您要发布的数据应该作为NSDictionary对象转换为Data传递。
答案 2 :(得分:0)
谢谢你@ Tj3N,你的回答很有帮助。
只需要更改编码类型。从NSASCIIStringEncoding到NSUTF8StringEncoding。 以下是更新的代码。
NSString *post =[NSString stringWithFormat:@"customerid=%@&productid=%@&vendorid=%@&quantity=%@",cid,PID,VID,QQ];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:@"URL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"str:%@",str);