我想将我的 JSON
发送到 URL(POST
和 GET
)。
NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];
我当前的请求代码不起作用。
NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];
[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];
[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];
使用 ASIHTTPRequest
是不是可靠的答案。
最佳答案
在 iOS 中发送 POST
和 GET
请求非常简单;并且不需要额外的框架。
POST
请求:
我们首先将 POST
的 body
(我们想发送的内容)创建为 NSString
,然后转换它到 NSData
.
NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
接下来,我们读取 postData
的 length
,以便在请求中传递它。
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
现在我们有了想要发布的内容,我们可以创建一个 NSMutableURLRequest
,并包含我们的 postData
。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
let post = "test=Message&this=isNotReal"
let postData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)
let postLength = String(postData!.count)
var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "POST"
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postData;
最后,我们可以发送我们的请求,并通过创建一个新的 NSURLSession
来读取回复:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
}] resume];
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
print("Request reply: \(requestReply!)")
}.resume()
GET
请求:
GET
请求基本上是一样的,只是没有 HTTPBody
和Content-Length
。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
}] resume];
var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "GET"
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
print("Request reply: \(requestReply!)")
}.resume()
附带说明,您可以通过将以下内容添加到我们的 NSMutableURLRequest
来添加 Content-Type
(和其他数据)。这可能是服务器在请求时需要的,例如 json .
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
也可以使用 [(NSHTTPURLResponse*)response statusCode]
读取响应代码。
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
更新: sendSynchronousRequest
在 ios9 中被弃用和 osx-elcapitan (10.11) 出。
NSURLResponse *requestResponse; NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@"requestReply: %@", requestReply);
关于objective-c - 如何发送 POST 和 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673127/