0

I have the following handler to respond to POST request:

[_webServer addHandlerForMethod:@"POST"
                           path:@"/"
                   requestClass:[GCDWebServerURLEncodedFormRequest class]
                   processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {

                       NSString* value = [[(GCDWebServerURLEncodedFormRequest*)request arguments] objectForKey:@"value"];
                       NSString* html = [NSString stringWithFormat:@"<html><body><p>%@</p></body></html>", value];
                       return [GCDWebServerDataResponse responseWithHTML:html];

                   }];

When the handler is triggered, NSString* value keeps giving me null. I am able to debug and view the GCDWebServerRequest object (screenshot).

enter image description here

There is a field _data which I wish to obtain.

May I know how to go about it?


Here is my POST request for reference:

 var request = require('request');
 request({
    url: 'http://XX.XX.XX.XX:8080',
    method: 'POST',
    headers:{
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: "12345678"
 }, function(error, response, body){
    console.log(body);
 });

I am using npm request to run the POST request. If I did value=test for my POST request, it gives me this error:

enter image description here

Huiting
  • 1,368
  • 7
  • 24

3 Answers3

0

Your GCDWebServer code is correct but the POST request you generate is not. The body must contain data formatted as a URL encoded form e.g. value=test.

Pol
  • 3,848
  • 1
  • 38
  • 55
  • I am developing for both android and iOS. The post request works for android though. I tried changing to `value=test` but it is giving me syntax error. I have edited my post on this – Huiting Jan 18 '18 at 00:22
0

For NPM request, if you wish to use content-type of x-www-form-urlencoded, you will have to call the parameter form instead of body.

Example:

request.post('http://service.com/upload', {form:{key:'value'}})
G.L.
  • 36
  • 4
0

You can subclass GCDWebServerRequest and override func write(_ data: Data) to access the body (e.g. for debugging this kind of issue). Just set requestClass to MyCustomPostRequest.self in addHandlerForMethod.

Toerndev
  • 715
  • 1
  • 6
  • 21