小编典典

如何发送POST和GET请求?

swift

我想将我JSON的网址发送到(POSTGET)。

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不是 一个容易回答。


阅读 359

收藏
2020-07-07

共1个答案

小编典典

在iOS中发送POSTGET请求非常容易。无需其他框架。


POST 请求:

首先,将我们POSTbody(按需发送的内容)创建为NSString,然后将其转换为NSData

目标

NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

接下来,我们阅读postDatalength,因此我们可以将其传递给请求。

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请求时,它基本上是相同的东西,只是 没有HTTPBodyContent-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()

另外,您可以Content- Type通过将以下内容添加到中来添加(和其他数据)NSMutableURLRequest。服务器在请求时可能需要这,例如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弃用
ios9OSX-
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);
2020-07-07