1

Mthod: Post Link: www.link.com Headers: 1: appKey="ABC" 2: Content-Type="text/csv" How to write the C# Script to send the data through post.?

EKNATH KULKARNI
  • 394
  • 1
  • 5
  • 13
  • I gone through link, I tried examples also. Their it is specified that the form.add method is used to upload the header but it wont work. And I need the post request by using UnityWebRequest. – EKNATH KULKARNI Aug 21 '18 at 05:46

2 Answers2

3
public void Request()
{
    try
    {
        string url = "www.link.com";

        var request = UnityWebRequest.Post(url, "");
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Accept", "text/csv");
        request.SetRequestHeader("appKey", "ABC");
        StartCoroutine(onResponse(request));
    }
    catch (Exception e) { Debug.Log("ERROR : " + e.Message); }
}
private IEnumerator onResponse(UnityWebRequest req)
{

    yield return req.SendWebRequest();
    if (req.isError)
      Debug.Log("Network error has occured: " + req.GetResponseHeader(""));
    else
        Debug.Log("Success "+req.downloadHandler.text );
        byte[] results = req.downloadHandler.data;
    Debug.Log("Second Success");
    // Some code after success

}

This code is worked for me...

Oneiros
  • 4,328
  • 6
  • 40
  • 69
EKNATH KULKARNI
  • 394
  • 1
  • 5
  • 13
  • You can use promises with the UnityWebRequest to improve the quality of your code, check this OpenSource unity plugin => https://github.com/proyecto26/RestClient – jdnichollsc Aug 31 '18 at 01:55
2

You could do something like this :

void Start()
{
    StartCoroutine(PostCrt());
}

IEnumerator PostCrt()
{
    WWWForm form = new WWWForm();
    form.AddField("appKey", "ABC");
    form.AddField("Content-Type", "text/csv");

    using (UnityWebRequest www = UnityWebRequest.Post("www.link.com", form))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Post Request Complete!");
        }
    }
}

Don't forget to call "using UnityEngine.Networking;" to be able to use UnityWebRequest.

Happy coding!

GhAyoub
  • 525
  • 4
  • 11