beeef
beeef

Reputation: 2702

Alamofire POST Request with Data

I'm developing an App with Swift for iOS and use the Alamofire Framework for HTTP(S) requests to an API. I already have an API "wrapper" written in PHP that works very well, but now I want to do that with Swift.

The API needs a nonce, my API key and a signature. The signature is calculated the right way and all components together should be in the request body.

Here the few lines of the PHP script that are working:

// generating nonce and signature
$mt = explode(' ', microtime());
$req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
$req['key'] = $key;
$req['signature'] = $this->get_signature($req['nonce']);

$post_data = http_build_query($req, '', '&');

static $ch = null;
if (is_null($ch))
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
}

curl_setopt($ch, CURLOPT_URL, 'https://example.org/api/');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

This is working like a charm. Alamofire should do this with even less lines of code, here's what I have:

let nonce = Int((Date().timeIntervalSince1970 * 1000.0).rounded())
if let signature = self.getSignature(nonce: nonce) {
    var params = [String: Any]()
    params["nonce"] = milliseconds
    params["key"] = key
    params["signature"] = signature

    let headers = [ "Content-Type": "application/x-www-form-urlencoded", "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0" ]
    Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON(completionHandler: { (repsonse) in
        // ...
    })
}

But the API always returns POST Only Endpoint as plaintext. With PHP I get a JSON array returned.

I tried to change the encoding types, added some custom header fields with different user-agents, set the Content-Type to application/x-www-form-urlencoded but nothing works.

Please help me if you know some solution to this problem.

Upvotes: 1

Views: 571

Answers (1)

beeef
beeef

Reputation: 2702

OMG! I found the answer to my problem.

The only problem was the missing / at the end of the URL. So e.g.

https://example.org/api/endpoint1

wasn't working, but

https://example.org/api/endpoint1/

is working now. So it absolutely has nothing to do with Alamofire itself. What a waste of time...

Upvotes: 0

Related Questions