Member-only story
How to send POST and GET request?
2 min readOct 5, 2020
Sending POST
and GET
requests in iOS is quite easy; and there's no need for an additional framework.
POST
Request:
We begin by creating our POST
's body
(ergo. what we'd like to send) as an NSString
, and converting it to NSData
.
NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
Next up, we read the postData
's length
, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
Now that we have what we’d like to post, we can create an NSMutableURLRequest
, and include our 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;