0

I've been working on this code to log in to my API. But every time I try to login using CURL I get the following error

{"message":"The request entity's media type 'multipart/form-data' is not supported for this resource.","exceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Credentials' from content with media type 'multipart/form-data'.","exceptionType":"System.Net.Http.UnsupportedMediaTypeException","stackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

My code is simply meant to login to my ERP system using a static username and password. The code is as follows:

$logindata = array(
    'name' => 'username',
    'password' => 'password'
);
$headers = array(
    'Content-Type' => 'application/json'
);
$ch = curl_init($url);
//        curl_setopt($ch,CURLOPT_COOKIEJAR, $this->cookie_jar);
//        curl_setopt($ch,CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, False);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, False);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch,CURLOPT_MAXREDIRS,0);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $logindata);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_error($ch);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

What am I doing wrong? and how can I fix it?

EDIT 1: I tried curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($logindata)); and while that stopped showing the error that I showed earlier, it still says that I'm not logged into the API and thus I'm still unable to use it further.

string(36) "{"message":"You are not logged in."}"

2
  • seems like an error on data type passed in the header, did you try other type like application/x-www-form-urlencoded ? or try like CURLOPT_POSTFIELDS, http_build_query($logindata)
    – fmsthird
    Commented Nov 30, 2020 at 14:38
  • @fmsthird I tried both and while the "http_build_query" worked in removing the error. it still says that I'm "not logged in" to the API. so I'm unable to do anything further with the API
    – Zyzzx
    Commented Dec 1, 2020 at 8:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.