How to send http post request in k6 for below example with --data-urlencode

curl -X POST ‘https://…’ -H ‘Content-Type: application/x-www-form-urlencoded’ -d “grant_type=xyz” -d “profile_id=xyz” --data-urlencode “cr_token@/path/exactpath”

1 Like

By default, if you pass a simple JS object to http.post() that doesn’t have a http.file() element in it, k6 will encode it as application/x-www-form-urlencoded. So, in your case, something like this should work:

import http from 'k6/http';

export default function () {
    let resp = http.post('https://httpbin.test.k6.io/anything', { 'grant_type': 'xyz', 'profile_id': 'xyz' });
    console.log(resp.body);
};

Alternatively, for more complicated use cases, you can build the string or ArrayBuffer body yourself and encode its parts with something like the JS built-in encodeURIComponent() function, or something like the form-urlencoded library from jslib.k6.io.

import http from 'k6/http';
import urlencode from 'https://jslib.k6.io/form-urlencoded/3.0.0/index.js';

export default function () {
    let body = urlencode({ 'grant_type': 'xyz', 'profile_id': 'xyz' });
    let params = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    let resp = http.post('https://httpbin.test.k6.io/anything', body, params);
    console.log(resp.body);
};
1 Like