如何在iOS中使用JSON发送POST数据?
How to send POST data using JSON in iOS?
我尝试在 Objectve-C 中使用 POST 请求向数据库添加一个条目。我的服务是:
@RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
@ResponseBody
boolean addEmployee(@ModelAttribute User user) {
try {
logger.log(Level.INFO, user.getCountry());
userDataService.addUser(user);
return true;
//return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return false;//new Status(0, e.toString());
}
}
当我在 Postman 上尝试这个时,它在 x-www-form-urlencoded
上运行良好。但是当我在 Objective-C 中尝试此操作时,没有任何反应。这是我尝试过的:
NSString *jsonInputString = @"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/user"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(@"%@", [error localizedDescription]);
}];
在完成块中,日志打印 "Could not connect to the server"。如何使用 JSON 数据调用服务?
Something like this should work
// 1: Create your URL, Session config and Session
NSString *jsonInputString = @"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/user"];
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2: Create NSMutableRequest object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
// 3: Create Jsondata object
NSError *error = nil;
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
// Asynchronously Api is hit here
NSURLSessionUploadTask *dataTask =
[session uploadTaskWithRequest:request
fromData:data
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(@"%@", data);
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"%@", json);
success(json);
}];
[dataTask resume]; // Executed First
我尝试在 Objectve-C 中使用 POST 请求向数据库添加一个条目。我的服务是:
@RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
@ResponseBody
boolean addEmployee(@ModelAttribute User user) {
try {
logger.log(Level.INFO, user.getCountry());
userDataService.addUser(user);
return true;
//return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return false;//new Status(0, e.toString());
}
}
当我在 Postman 上尝试这个时,它在 x-www-form-urlencoded
上运行良好。但是当我在 Objective-C 中尝试此操作时,没有任何反应。这是我尝试过的:
NSString *jsonInputString = @"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/user"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(@"%@", [error localizedDescription]);
}];
在完成块中,日志打印 "Could not connect to the server"。如何使用 JSON 数据调用服务?
Something like this should work
// 1: Create your URL, Session config and Session
NSString *jsonInputString = @"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/user"];
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2: Create NSMutableRequest object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
// 3: Create Jsondata object
NSError *error = nil;
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
// Asynchronously Api is hit here
NSURLSessionUploadTask *dataTask =
[session uploadTaskWithRequest:request
fromData:data
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(@"%@", data);
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"%@", json);
success(json);
}];
[dataTask resume]; // Executed First