数据在 Postman 应用程序中有效,但在下面的代码中无效,即我收到底部提到的错误。我无法理解代码中的错误在哪里。提前致谢。
Postman数据截图如下:
标题:
正文:
代码如下:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://apifm.azurewebsites.net/api/Checkout/CheckoutOrders"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"Bearer VMuEUFkfBSAfMGhCHYVVEpnN7PWj80RdpSBEJ7gPVtaFQ9P6OHDfKepQcEi3dipPAu3rTHQntRRqbktAQur4rIFIEw05DeKwhhAblVBbbWM8Vzx9HGD9Asmv-cRehQbTKnGlvvT7NuYXn1lsSdoRSa4Ut0JvxYZeZRAmygLaylleT9QWrlKCCA1_rM9GJ_KZFzOAG6VwP70jn0UJaHQChPNLB1Ape_KjMlXiqWv0AjyAiGR4QwSOWNVYIv8QdhuhvSoaQFpcipKUvIyG5fmPKyflETswjPTBF5tZhEdP_kBg6xAIPb7pfJqtbxzyvJ7KilAc84PuByWHogwBIvq0vB4x201b9dBwrJfsxKQB0yEJd9AwqtW8iGFuEdHIfkjyCXjsKAIx4szFS6gaOcQDPTsob25TSEiYAMMlbis7Olbv0lTd6-RSB1Q1KFFERIXszCKCdvznpVMdCST1zaQ3ug" forHTTPHeaderField:@"Authorization"];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:@"39399393" forKey:@"UserPhone"];
[postDict setValue:@"Manohar" forKey:@"firstName"];
[postDict setValue:@"Adhikari" forKey:@"lastName"];
[postDict setValue:@"testman@foodmandu.com" forKey:@"Email"];
[postDict setValue:@"9988989800" forKey:@"Phone1"];
[postDict setValue:@"" forKey:@"Phone2"];
[postDict setValue:@"na" forKey:@"Organization"];
[postDict setValue:@"Naxal, Kathmandu 44600, Nepal" forKey:@"Address1"];
[postDict setValue:@"this is new address" forKey:@"Address2"];
[postDict setValue:@"1" forKey:@"PaymentOption"];
[postDict setValue:@"DELIVERY" forKey:@"DeliveryType"];
[postDict setValue:@"0" forKey:@"OrderId"];
[postDict setValue:@"128" forKey:@"VendorId"];
[postDict setValue:@"3108" forKey:@"ShippingAddressId"];
[postDict setValue:@"0" forKey:@"BillingAddressId"];
[postDict setValue:@"Here goes special instruction of the customer" forKey:@"OrderNote"];
[postDict setValue:@"null" forKey:@"DeliveryDateTime"];
[postDict setValue:@"192.168.0.5" forKey:@"CustomerIp"];
[postDict setValue:@"54" forKey:@"DeliveryCharge"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:@"jsonRequest=%@", urlString];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSLog(@"response--%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else{
NSLog(@"error--%@",connectionError);
}
}];
下面是我得到的错误:
response--{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at Foodmandu.Models.DAL.DALCheckOut.checkOutOrders(JObject Jobj, Int32 UserId)\r\n at Foodmandu.Areas.API.CheckOutController.CheckOutOrders(JObject Jobj)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}
最佳答案
我的建议 - 如果您不想使用 AFNetworking,请将 AFURLRequestSerialization 作为依赖项。用于通过它创建请求。在您的项目中仅添加 AFURLRequestSerialization.h/m 文件(+ 许可文件)。或者自己写序列化代码。
<p></p>
<pre><code>NSDictionary *postDict = @{
@"UserPhone" : @"39399393",
@"firstName" : @"Manohar",
....
};
AFURLRequestSerialization *serializer = [AFURLRequestSerialization serializer];
NSString *urlString = @"https://YOUR_URL";
NSError *error = nil;
NSMutableURLRequest *request = [serializer requestWithMethod:@"POST"
URLString:urlString
parameters:postDict
error:error];
if (error) {
// check error
}
// Your custom http-header values
[request setValue:@"VALUE" forHTTPHeaderField:@"KEY"];
// send request
[NSURLConnection sendAsynchronousRequest:....];
</code></pre>
<p></p>
关于ios - 发布 header 数据和 x-www-form-urlencoded 数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31292204/