iosobjective-cxcodensurlrequest

How to send HTTP body plain text for GET method?


I had a problem, I use the iGDB REST API which need to send some plain text for some endpoints with GET method.

There is no problem with PostMan (by selecting "Body" > "raw" & paste my query), but when I try with Objective-C, an error appear telling me "GET method must not have a body"...

PostMan example

Here is the code used in my app:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL"]];
[request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"GET"];
[request setHTTPBody:[@"sort popularity desc;" dataUsingEncoding:NSUTF8StringEncoding]];

EDIT 02/10/2019

Trying to add each filters in headers not working...

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL"]];
[request setValue:[[@"id,name,first_release_date,release_dates,cover,platforms" dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0] forHTTPHeaderField:@"fields"];
[request setValue:[[@"popularity desc" dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0] forHTTPHeaderField:@"sort"];
[request setValue:[[@"5" dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0] forHTTPHeaderField:@"limit"];
[request setValue:[[@"0" dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0] forHTTPHeaderField:@"offset"];

Thanks in advance for any replies !


Solution

  • It's no longer possible to send a GET request with a body, you'll have to send the data via the query string of the URL, either by building the string manually or with the help of NS(Mutable)URLComponents.


    As per the iOS 13 release notes, GET requests are no longer allowed to have a body:

    All URLSessionTask instances with a GET HTTP method that contain a body now produce the error NSURLErrorDataLengthExceedsMaximum. (46025234)

    This makes URLSession more conformant with the HTTP/1.1 RFC:

    A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.