I am trying to request a data from a node.js server by feeding it jsondata from a unity script but the connection keeps failing and im not sure if it’s my code issue. The api definitely works with the json data as I tried it in curl.
public IEnumerator Post(string url,string jsonData)
{
using (UnityWebRequest www = UnityWebRequest.PostWwwForm(url, jsonData))
{
www.method = UnityWebRequest.kHttpVerbPOST;
www.certificateHandler = new BypassCertificate();
byte[] dataByte = new System.Text.UTF8Encoding().GetBytes(jsonData);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(dataByte);
www.SetRequestHeader("Content-Type", "application/json");
//if (expectedReturn != null) //always have download handler to handle error data being sent over
www.downloadHandler = (DownloadHandlerBuffer)new DownloadHandlerBuffer();
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
// Handle error
Debug.LogError(www.error);
}
else
{
// Handle successful response
Debug.Log("Response: " + www.downloadHandler.text);
}
}
}
}
// Class to bypass certificate validation
public class BypassCertificate : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
// Always return true to bypass certificate validation
return true;
}
}
New contributor
ylhere is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.